It is the hard version of the problem. The only difference is that in this version $1 \le n \le 300$.

In the cinema seats can be represented as the table with $n$ rows and $m$ columns. The rows are numbered with integers from $1$ to $n$. The seats in each row are numbered with consecutive integers from left to right: in the $k$-th row from $m (k - 1) + 1$ to $m k$ for all rows $1 \le k \le n$.

$1$

$2$

$\cdots$

$m - 1$

$m$

$m + 1$

$m + 2$

$\cdots$

$2 m - 1$

$2 m$

$2m + 1$

$2m + 2$

$\cdots$

$3 m - 1$

$3 m$

$\vdots$

$\vdots$

$\ddots$

$\vdots$

$\vdots$

$m (n - 1) + 1$

$m (n - 1) + 2$

$\cdots$

$n m - 1$

$n m$

The table with seats indices

There are $nm$ people who want to go to the cinema to watch a new film. They are numbered with integers from $1$ to $nm$. You should give exactly one seat to each person.

It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $i$-th person has the level of sight $a_i$. Let's define $s_i$ as the seat index, that will be given to $i$-th person. You want to give better places for people with lower sight levels, so for any two people $i$, $j$ such that $a_i < a_j$ it should be satisfied that $s_i < s_j$.

After you will give seats to all people they will start coming to their seats. In the order from $1$ to $nm$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.

Let's consider an example: $m = 5$, the person has the seat $4$ in the first row, the seats $1$, $3$, $5$ in the first row are already occupied, the seats $2$ and $4$ are free. The inconvenience of this person will be $2$, because he will go through occupied seats $1$ and $3$.

Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).


-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Description of the test cases follows.

The first line of each test case contains two integers $n$ and $m$ ($1 \le n, m \le 300$) — the number of rows and places in each row respectively.

The second line of each test case contains $n \cdot m$ integers $a_1, a_2, \ldots, a_{n \cdot m}$ ($1 \le a_i \le 10^9$), where $a_i$ is the sight level of $i$-th person.

It's guaranteed that the sum of $n \cdot m$ over all test cases does not exceed $10^5$.


-----Output-----

For each test case print a single integer — the minimal total inconvenience that can be achieved.


-----Examples-----

Input
7
1 2
1 2
3 2
1 1 2 2 3 3
3 3
3 4 4 1 1 1 1 1 2
2 2
1 1 2 1
4 2
50 50 50 50 3 50 50 50
4 2
6 6 6 6 2 2 9 6
2 9
1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3
Output
1
0
4
0
0
0
1


-----Note-----

In the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is $1$.

In the second test case the optimal seating looks like this:

In the third test case the optimal seating looks like this:

The number in a cell is the person's index that sits on this place.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Sorting

Amortized analysis

Implementation

Greedy algorithms

Data structures


Solutions:
from collections import defaultdict
import math

class SegmentTree:

	def __init__(self, n):
		self.n = self.next_power(n)
		self.size = self.n * 2 - 1
		self.ZERO = 0
		self.tree = [self.ZERO] * self.size

	def next_power(self, x):
		return 1 if x == 0 else 2 ** math.ceil(math.log2(x))

	def parent(self, i):
		return (i - 1) // 2 if i != 0 else None

	def l_child(self, i):
		return i * 2 + 1

	def r_child(self, i):
		return i * 2 + 2

	def set(self, i, val):
		i = self.n - 1 + i
		self.tree[i] = self.set_val(val)
		self.up(i)

	def set_val(self, val):
		return val

	def up(self, i):
		p_i = self.parent(i)
		if p_i is not None:
			l_i = self.l_child(p_i)
			r_i = self.r_child(p_i)
			self.tree[p_i] = self.update(self.tree[l_i], self.tree[r_i])
			self.up(p_i)

	def update(self, l_val, r_val):
		return l_val + r_val

	def get(self, l, r):
		return self.down(0, l, r, 0, self.n)

	def down(self, i, l, r, lx, rx):
		if lx >= l and rx <= r:
			return self.tree[i]
		if rx <= l or lx >= r:
			return 0
		m = (rx + lx) // 2
		(l_i, r_i) = (self.l_child(i), self.r_child(i))
		return self.update(self.down(l_i, l, r, lx, m), self.down(r_i, l, r, m, rx))

def get_coords(pos, m):
	row = pos // m
	col = pos - row * m
	return (row, col)

def solve(n, m, a):
	cnt = defaultdict(list)
	for i in range(len(a) - 1, -1, -1):
		cnt[a[i]].append(i)
	matrix = [[0] * m for _ in range(n)]
	start_pos = 0
	keys = sorted(cnt.keys())
	for key in keys:
		while cnt[key]:
			(curr_row, curr_col) = get_coords(start_pos, m)
			max_col = min(m, curr_col + len(cnt[key]))
			for col in range(max_col - 1, curr_col - 1, -1):
				matrix[curr_row][col] = cnt[key].pop()
				start_pos += 1
	num_inconv = 0
	for row in matrix:
		row_with_index = [(num, i) for (i, num) in enumerate(row)]
		row_with_index.sort()
		tree = SegmentTree(len(row_with_index))
		for (_, i) in row_with_index:
			num_inconv += tree.get(0, i)
			tree.set(i, 1)
	return num_inconv
t = int(input())
for _ in range(t):
	(n, m) = [int(val) for val in input().split()]
	a = [int(val) for val in input().split()]
	print(solve(n, m, a))


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
import random

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	cnt = []
	while n % 2 == 0:
		cnt.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt.append(i)
			n = n / i
	if n > 2:
		cnt.append(int(n))
	return cnt

def primeFactorsCount(n):
	cnt = 0
	while n % 2 == 0:
		cnt += 1
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt += 1
			n = n // i
	if n > 2:
		cnt += 1
	return cnt

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	i = 2
	while i * i <= n:
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
		i += 1
	pr = []
	for i in range(0, n + 1):
		if primes[i]:
			pr.append(i)
	return pr

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def sod(n):
	s = 0
	while n > 0:
		s += n % 10
		n //= 10
	return s

def inv(n, m):
	return pow(n, m - 2, m)

def countcon2(s1, s2, i):
	n = len(s1)
	cnt = 0
	while i < n and s1[i] == s2[i]:
		i += 1
		cnt += 1
	return cnt
for xyz in range(0, int(input())):
	(n, m) = map(int, input().split())
	mat = list(map(int, input().split()))
	for i in range(0, n * m):
		mat[i] = [mat[i], i]
	ans = 0
	mat.sort()
	for row in range(0, n):
		l = mat[row * m:(row + 1) * m]
		for i in range(1, m):
			base = m * row
			for j in range(0, i):
				if l[j][1] < l[i][1] and l[j][0] < l[i][0]:
					ans += 1
	print(ans)


import sys

def input():
	return sys.stdin.readline().rstrip('\r\n')

def maps():
	return [int(i) for i in input().split()]
from collections import defaultdict
from math import ceil

def func(n, m, a):
	A = sorted([(j, i) for (i, j) in enumerate(a)], key=lambda x: (x[0], -x[1]))
	s = [0] * m
	for i in range(m):
		s[A[i][1]] = i
	vis = [0] * m
	ans = 0
	for i in range(m):
		vis[s[i]] = 1
		ans += sum(vis[:s[i]])
	return ans
for i in range(*maps()):
	(n, m) = maps()
	a = sorted(([j, i] for (i, j) in enumerate(maps())))
	for i in range(n * m):
		a[i][1] = -a[i][1]
	ans = 0
	for i in range(n):
		x = a[i * m:i * m + m]
		x.sort()
		for j in range(m):
			ans += sum((1 if x[j][1] < x[k][1] else 0 for k in range(j)))
	print(ans)


from __future__ import print_function
from math import *
from collections import deque
import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())

def ss(a, b):
	return a + b

class SegmentTree:

	def __init__(self, data, default=0, func=max):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
for _ in range(inp()):
	(n, m) = invr()
	a = inlt()
	d = {}
	dd = {}
	t = sorted(a)
	for i in range(n * m):
		if t[i] not in dd:
			dd[t[i]] = deque()
			dd[t[i]].append(deque())
			dd[t[i]][-1].append(i + 1)
		else:
			if (dd[t[i]][-1][-1] - 1) % m >= i % m:
				dd[t[i]].append(deque())
			dd[t[i]][-1].append(i + 1)
	arr = [0] * (n * m)
	c = 0
	for i in dd:
		d[i] = deque()
		for j in range(len(dd[i])):
			for k in range(len(dd[i][j]) - 1, -1, -1):
				d[i].append(dd[i][j][k])
		d[i].reverse()
	st = SegmentTree(arr, 0, ss)
	for i in a:
		k = d[i].pop()
		r = (k - 1) // m
		x = (k - 1) % m
		start = m * r
		c += st.query(start, start + x)
		st[k - 1] = 1
	print(c)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().strip().split())
	arr = [[int(x)] for x in input().strip().split()]
	for x in range(n * m):
		arr[x].append(x + 1)
	arr.sort()
	cnt = 0
	for r in range(0, n * m, m):
		for i in range(r, r + m):
			for j in range(r, i):
				if arr[j][0] < arr[i][0] and arr[j][1] < arr[i][1]:
					cnt += 1
	print(cnt)


from math import sqrt, gcd, ceil, floor, log, factorial
from itertools import permutations, combinations
from collections import Counter, defaultdict
import collections, sys, threading
import collections, sys, threading

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def msi():
	return map(str, input().split())

def li():
	return list(mi())
t = ii()
for _ in range(t):
	(n, m) = mi()
	a = li()
	ind = sorted(a)
	rowind = []
	for i in range(n * m):
		rowind.append([a[i], i])
	rowind.sort()
	d = defaultdict(list)
	row = defaultdict(list)
	for i in range(n * m):
		d[ind[i], i // m].append(i % m)
		row[rowind[i][0], rowind[i][1]].append(i // m)
	for key in d:
		d[key].sort()
	for key in row:
		row[key].sort()
	ans = 0
	cnt = [0] * (m * n)
	for i in range(n * m):
		rown = row[a[i], i].pop()
		seat = d[a[i], rown].pop()
		ans += sum(cnt[m * rown:seat + m * rown])
		cnt[seat + m * rown] = 1
	print(ans)


T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	a = list(enumerate(map(int, input().split())))
	a.sort(key=lambda x: (x[1], x[0]))
	first = 0
	num = a[0][1]
	for i in range(1, n * m):
		if a[i][1] != num:
			a[first:i] = reversed(a[first:i])
			first = i
			num = a[i][1]
		if i % m == m - 1:
			a[first:i + 1] = reversed(a[first:i + 1])
			first = i + 1
	indxs = [None] * (n * m)
	for i in range(n * m):
		indxs[a[i][0]] = i
	cinema = [[0] * m for _ in range(n)]
	ans = 0
	for i in range(n * m):
		row = indxs[i] // m
		seat = indxs[i] % m
		ans += sum(cinema[row][:seat])
		cinema[row][seat] = 1
	print(ans)


import sys
import bisect
input = sys.stdin.readline
tests = int(input())
for test in range(tests):
	(n, m) = map(int, input().split())
	persons = list(map(int, input().split()))
	sortedPersons = sorted(persons)
	maxInRow = []
	for row in range(n):
		maxInRow.append(sortedPersons[(row + 1) * m - 1])
	rowForLevel = {}
	lastLevel = 0
	for level in sortedPersons:
		if level > lastLevel:
			for (idx, maxInThisRow) in enumerate(maxInRow):
				if level <= maxInThisRow:
					rowForLevel[level] = idx
					break
			lastLevel = level
	inconvenience = 0
	seatmap = [[] for i in range(n)]
	for (idx, person) in enumerate(persons):
		row = rowForLevel[person]
		inconvenience += len([seated for seated in seatmap[row] if seated < person])
		bisect.insort(seatmap[row], person)
		if person == maxInRow[row]:
			if seatmap[row].count(person) == sortedPersons[row * m:(row + 1) * m].count(person):
				rowForLevel[person] += 1
	print(inconvenience)


import os, sys
from io import BytesIO, IOBase
from collections import deque, Counter, defaultdict as dft
from heapq import heappop, heappush
from math import log, sqrt, factorial, cos, tan, sin, radians, log2, ceil, floor, gcd
from bisect import bisect, bisect_left, bisect_right
from decimal import *
import sys, threading
from itertools import permutations, combinations
from copy import deepcopy
input = sys.stdin.readline

def modI(a, m):
	m0 = m
	y = 0
	x = 1
	if m == 1:
		return 0
	while a > 1:
		q = a // m
		t = m
		m = a % m
		a = t
		t = y
		y = x - q * y
		x = t
	if x < 0:
		x += m0
	return x
ii = lambda : int(input())
si = lambda : input().rstrip()
mp = lambda : map(int, input().split())
ms = lambda : map(str, input().strip().split(' '))
ml = lambda : list(mp())
mf = lambda : map(float, input().split())
alphs = 'abcdefghijklmnopqrstuvwxyz'

def solve():
	(n, m) = mp()
	ls = ml()
	arr = []
	res = 0
	for i in range(n * m):
		arr.append([ls[i], i + 1])
	arr.sort()
	st = 0
	for i in range(n * m):
		for j in range(st, i):
			if abs(arr[j][1]) < abs(arr[i][1]) and arr[j][0] != arr[i][0]:
				res += 1
		if (i + 1) % m == 0:
			st += m
	print(res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=gcd):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
tc = 1
tc = ii()
for i in range(tc):
	solve()


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10001)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10000):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

class LazySegUpdate:

	def __init__(self, N):
		self.N = N
		n = 4 * N
		self.tree = [0] * n
		self.lazy = [0] * n

	def queryHelper(self, index, s, e, l, r):
		if self.lazy[index]:
			update = self.lazy[index]
			self.lazy[index] = 0
			self.tree[index] = max(self.tree[index], update)
			if s != e:
				self.lazy[2 * index] = max(self.lazy[2 * index], update)
				self.lazy[2 * index + 1] = max(self.lazy[2 * index + 1], update)
		if s > e or s > r or e < l:
			return 0
		if s >= l and e <= r:
			return self.tree[index]
		mid = (s + e) // 2
		return max(self.queryHelper(2 * index, s, mid, l, r), self.queryHelper(2 * index + 1, mid + 1, e, l, r))

	def updateHelper(self, index, s, e, l, r, h):
		if self.lazy[index]:
			update = self.lazy[index]
			self.lazy[index] = 0
			self.tree[index] = max(self.tree[index], update)
			if s != e:
				self.lazy[2 * index] = max(self.lazy[2 * index], update)
				self.lazy[2 * index + 1] = max(self.lazy[2 * index + 1], update)
		if s > e or s > r or e < l:
			return
		if s >= l and e <= r:
			self.tree[index] = max(self.tree[index], h)
			if s != e:
				self.lazy[2 * index] = max(self.lazy[2 * index], h)
				self.lazy[2 * index + 1] = max(self.lazy[2 * index + 1], h)
			return
		mid = (s + e) // 2
		self.updateHelper(2 * index, s, mid, l, r, h)
		self.updateHelper(2 * index + 1, mid + 1, e, l, r, h)
		self.tree[index] = max(self.tree[2 * index], self.tree[2 * index + 1])

	def query(self, l, r):
		return self.queryHelper(1, 0, self.N - 1, l, r - 1)

	def update(self, l, r, h):
		self.updateHelper(1, 0, self.N - 1, l, r - 1, h)

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = n
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] >= key:
			res = mid
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
t = 1
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = []
	for i in range(n * m):
		b.append([a[i], i])
	b.sort()
	ans = 0
	for i in range(0, n * m, m):
		s = SortedList()
		c = []
		for j in range(i, i + m):
			c.append([b[j][0], n * m - b[j][1]])
		c.sort()
		for j in range(i, i + m):
			el = n * m - c[j - i][1]
			ans += s.bisect_left(el)
			s.add(el)
	print(ans)


import bisect
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	h = [[] for i in range(n)]
	q = {i: [] for i in set(l)}
	p = sorted(l)
	t = 0
	for i in range(n):
		for j in range(m):
			q[p[t]].append(i)
			t += 1
	for i in q:
		q[i].reverse()
	s = 0
	for i in l:
		t = q[i].pop()
		j = bisect.bisect_left(h[t], i)
		s += j
		h[t].insert(j, i)
	print(s)


import collections
import math
import itertools
import sys
import time

def fast_input():
	return sys.stdin.readline().strip()
input = fast_input

def ints_input():
	return list((int(x) for x in input().split()))

def int_input():
	return int(input())

def count_inversions_and_sort(l):
	if len(l) == 1:
		return (l, 0)
	else:
		split = len(l) // 2
		(l_1, l_2) = (l[:split], l[split:])
		(s_1, i_1) = count_inversions_and_sort(l_1)
		(s_2, i_2) = count_inversions_and_sort(l_2)
		p_1 = p_2 = 0
		inversions = 0
		while p_1 < len(s_1) or p_2 < len(s_2):
			if p_1 == len(s_1):
				l[p_1 + p_2] = s_2[p_2]
				p_2 += 1
				inversions += p_1
			elif p_2 == len(s_2):
				l[p_1 + p_2] = s_1[p_1]
				p_1 += 1
			else:
				x_1 = s_1[p_1]
				x_2 = s_2[p_2]
				if x_1 < x_2:
					l[p_1 + p_2] = s_1[p_1]
					p_1 += 1
				else:
					l[p_1 + p_2] = s_2[p_2]
					p_2 += 1
					inversions += p_1
		return (l, inversions + i_1 + i_2)

def solve():
	(n, m) = ints_input()
	a = ints_input()
	people_by_s = collections.defaultdict(list)
	for (i, a) in enumerate(a):
		people_by_s[a].append(i)
	sorted_sights = sorted(list(people_by_s.keys()))
	rows = [[None for _ in range(m)] for _ in range(n)]
	row = 0
	col = 0
	for s in sorted_sights:
		if col == m:
			col = 0
			row += 1
		total = len(people_by_s[s])
		if col + total > m:
			in_this_row = m - col
		else:
			in_this_row = total
		in_last_row = (total - in_this_row) % m
		for p in people_by_s[s][:in_this_row][::-1]:
			if col == m:
				col = 0
				row += 1
			rows[row][col] = p
			col += 1
		row += (total - in_this_row - in_last_row) // m
		if in_last_row:
			for p in people_by_s[s][-in_last_row:][::-1]:
				if col == m:
					col = 0
					row += 1
				rows[row][col] = p
				col += 1
	non_none_rows = [x for x in rows if x[0] is not None]
	print(sum((count_inversions_and_sort(row)[1] for row in non_none_rows)))
if True:
	for _ in range(int_input()):
		solve()
else:
	solve()


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound

def so():
	return int(input())

def st():
	return input()

def mj():
	return map(int, input().strip().split(' '))

def msj():
	return map(str, input().strip().split(' '))

def le():
	return list(map(int, input().split()))

def lebe():
	return list(map(int, input()))

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()

def joro(L):
	return ''.join(map(str, L))

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def npr(n, r):
	return factorial(n) // factorial(n - r) if n >= r else 0

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def tir(a, b, c):
	if 0 == c:
		return 1
	if len(a) <= b:
		return 0
	if c != -1:
		return tir(a, 1 + b, c + a[b]) or tir(a, b + 1, c - a[b]) or tir(a, 1 + b, c)
	else:
		return tir(a, 1 + b, a[b]) or tir(a, b + 1, -a[b]) or tir(a, 1 + b, -1)

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = -1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def wubu(m):
	import math as my
	d = 0
	while not m % 2:
		m = m // 2
		d = 1 + d
	for i in range(3, int(my.sqrt(m)) + 1, 2):
		while not m % i:
			m = m // i
			d = 1 + d
	return int(m > 1) + d

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	li = []
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, len(prime)):
		if prime[p]:
			li.append(p)
	return li

def primefactors(n):
	factors = []
	while n % 2 == 0:
		factors.append(2)
		n //= 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			factors.append(i)
			n //= i
	if n > 2:
		factors.append(n)
	return factors

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def tr(n):
	return n * (n + 1) // 2

def iu():
	import sys
	input = sys.stdin.readline
	import math as my
	(p, q) = mj()
	(c, bec) = (0, 0)
	M = []
	L = le()
	for i in L:
		M.append((i, c))
		c = 1 + c
	M.sort()
	for i in range(0, q * p, q):
		Z = M[i:q + i]
		Z.sort(key=lambda p: p[1])
		for up in range(1, q, 1):
			op = 0
			while up > op:
				if Z[up][0] > Z[op][0]:
					bec = 1 + bec
				op = 1 + op
	print(bec)

def main():
	for i in range(so()):
		iu()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline

class Bit:

	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def add(self, i, x):
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

def f(l, st, en):
	tmp = []
	for j in range(st, en):
		tmp.append(j)
		if j % M == M - 1:
			while tmp:
				k = tmp.pop()
				mm = l.pop()
				S[mm] = k
			tmp = []
	while tmp:
		k = tmp.pop()
		mm = l.pop()
		S[mm] = k
(T,) = map(int, input().split())
for _ in range(T):
	(N, M) = map(int, input().split())
	X = list(map(int, input().split()))
	Z = []
	S = [0] * N * M
	for i in range(N * M):
		Z.append((i, X[i], X[i] * 10 ** 6 + (M - i)))
	Z.sort(key=lambda x: x[2])
	b = Z[0][1]
	tmp = []
	start = 0
	for i in range(N * M):
		(j, a, _) = Z[i]
		if a != b:
			f(tmp, start, i)
			tmp = []
			start = i
		tmp.append(j)
		b = a
	f(tmp, start, N * M)
	bt = [Bit(M) for _ in range(N)]
	R = 0
	for i in range(N * M):
		kk = S[i] // M
		R += bt[kk].sum(S[i] % M + 1)
		bt[kk].add(S[i] % M + 1, 1)
	print(R)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def input_list():
	return list(map(int, input().split()))

def input_string():
	s = input()
	return list(s[:len(s) - 1])

def input_int_gen():
	return map(int, input().split())

def merge_sort(list):
	list_length = len(list)
	if list_length == 1:
		return (list, 0)
	mid_point = list_length // 2
	(left_partition, left_res) = merge_sort(list[:mid_point])
	(right_partition, right_res) = merge_sort(list[mid_point:])
	(merged, merge_res) = merge(left_partition, right_partition)
	return (merged, left_res + right_res + merge_res)

def merge(left, right):
	output = []
	i = j = 0
	res = 0
	while i < len(left) and j < len(right):
		if left[i] >= right[j]:
			output.append(left[i])
			i += 1
		else:
			output.append(right[j])
			j += 1
			res += len(left) - i
	output.extend(left[i:])
	output.extend(right[j:])
	return (output, res)
from bisect import bisect_left
tests = inp()
for _ in range(tests):
	(n, m) = input_int_gen()
	a = input_list()
	sorted_a = sorted(a)
	splits = []
	holds = []
	for i in range(1, n):
		k = sorted_a[m * i - 1]
		t = bisect_left(sorted_a, k)
		splits.append(k)
		holds.append(min(m * i - t, m))
	splited_a = [[] for _ in range(n)]
	actual_hold = [0 for _ in range(n - 1)]
	for i in a:
		t = bisect_left(splits, i)
		while t < len(splits) and i == splits[t] and (actual_hold[t] >= holds[t]):
			t += 1
		splited_a[t].append(i)
		if t < len(splits) and i == splits[t]:
			actual_hold[t] += 1
	res = sum((merge_sort(x)[1] for x in splited_a))
	print(res)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	for i in range(n * m):
		d[a[i]] = d.get(a[i], [])
		d[a[i]].append(i)
	o = [[] for _ in range(n)]
	i = k = 0
	dd = sorted(d)
	for j in range(n):
		while len(d[dd[i]][k:]) + len(o[j]) < m:
			o[j] += d[dd[i]][k:][::-1]
			k = 0
			i += 1
		kk = m - len(o[j])
		o[j] += d[dd[i]][k:k + kk][::-1]
		k += kk
	d = {}
	for i in range(n):
		for j in range(m):
			d[o[i][j]] = (i, j)
	c = 0
	s = [[False] * m for _ in range(n)]
	for k in range(n * m):
		(i, j) = d[k]
		s[i][j] = True
		c += sum(s[i][:j])
	print(c)


import sys
input = sys.stdin.buffer.readline
from bisect import bisect_left, bisect_right

def queries(l, r):
	count = 0
	while l <= r:
		if l % 2 == 1:
			count += seg_tree[l]
			l += 1
		if r % 2 == 0:
			count += seg_tree[r]
			r -= 1
		l = l >> 1
		r = r >> 1
	return count

def update(indx):
	seg_tree[indx] += 1
	indx = indx >> 1
	while indx >= 1:
		seg_tree[indx] = seg_tree[2 * indx] + seg_tree[2 * indx + 1]
		indx = indx >> 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	N = n * m
	arr = list(map(int, input().split()))
	brr = arr[:]
	brr.sort()
	seg_tree = [0 for i in range(2 * N)]
	d = [{} for i in range(n + 3)]
	di = {}
	ans = 0
	for i in range(N):
		nisana = bisect_left(brr, arr[i])
		if arr[i] not in di:
			di[arr[i]] = 1
		else:
			nisana += di[arr[i]]
			di[arr[i]] += 1
		l = nisana // m
		if arr[i] not in d[l]:
			d[l][arr[i]] = 1
		else:
			d[l][arr[i]] += 1
		ans += queries(N + l * m, nisana + N)
		ans -= d[l][arr[i]] - 1
		update(nisana + N)
	print(ans)


import sys
input = sys.stdin.buffer.readline

def solve():
	indices = list(range(N * M))
	indices.sort(key=lambda i: A[i])
	indexOf = {}
	for (i, val) in enumerate(indices):
		indexOf[val] = i
	indices.sort(key=lambda i: (A[i], indexOf[i] // M, -i))
	ans = 0
	row = [0] * M
	for i in range(N):
		for j in range(M):
			row[j] = indices[i * M + j]
		for j in range(M):
			for k in range(j):
				if row[k] < row[j]:
					ans += 1
	return ans
test_cases = int(input())
for test_case in range(test_cases):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	print(solve())


t = int(input())
from heapq import heappush, heappop
while t:
	t -= 1
	(n, m) = [int(x) for x in input().split()]
	arr1 = [int(x) for x in input().split()]
	arr = sorted(arr1)
	d = {}
	filled = [[False for x in range(m)] for x in range(n)]
	for row in range(1, n + 1):
		for col in range(1, m + 1):
			index = m * (row - 1) + col - 1
			if arr[index] not in d:
				d[arr[index]] = [(row, -col)]
			else:
				heappush(d[arr[index]], (row, -col))
	ans = 0
	for item in arr1:
		(row, col) = heappop(d[item])
		col *= -1
		row -= 1
		col -= 1
		for j in range(col):
			if filled[row][j]:
				ans += 1
		filled[row][col] = True
	print(ans)


import sys
input = sys.stdin.readline

def s(a):
	n = len(a)
	r = 0
	for i in range(n):
		if a[i] == 0:
			if i > 0 and a[i - 1] == 1 or (i + 1 < n and a[i + 1] == 1):
				r += 2
			else:
				r += 1
	return r

def solve():
	(n, m) = map(int, input().split())
	i = 0
	a = [0] * (n * m)
	for v in map(int, input().split()):
		a[i] = (v, i)
		i += 1
	a.sort()
	b = [0] * (n * m)
	for i in range(n):
		j = i * m
		k = j + m
		while j < k:
			z = j + 1
			v = a[j][0]
			while z < k and a[z][0] == v:
				z += 1
			for v in range(z - j):
				b[a[z - v - 1][1]] = j + v
			j = z
	h = [[0] * m for i in range(n)]
	r = 0
	for i in range(n * m):
		j = b[i]
		(y, x) = divmod(j, m)
		z = x
		H = h[y]
		while z >= 0:
			r += H[z]
			z = (z & z + 1) - 1
		z = x
		while z < m:
			H[z] += 1
			z = z | z + 1
	print(r)
for i in range(int(input())):
	solve()


from sys import stdin
input = stdin.readline

def answer():
	s = [[0 for i in range(m)] for j in range(n)]
	(ans, ind) = (0, 0)
	for i in range(n):
		for j in range(m):
			x = d[ind] // m
			y = d[ind] % m
			value = 0
			for k in range(y + 1):
				value += s[x][k]
			ans += value
			s[x][y] = 1
			ind += 1
	return ans
for T in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	x = [[a[i], i] for i in range(len(a))]
	x.sort()
	d = dict()
	ind = 0
	for i in range(n):
		b = []
		for j in range(m):
			b.append(x[ind + j][:])
		b.sort(key=lambda x: [x[0], -x[1]])
		for j in range(m):
			d[b[j][1]] = ind + j
		ind += m
	print(answer())


import sys, math
from collections import Counter, deque
input = sys.stdin.buffer.readline

class fenwick:

	def __init__(self, n):
		self.n = n
		self.fw = [0] * (n + 1)

	def add(self, u, val):
		while u <= self.n:
			self.fw[u] += val
			u += u & -u

	def psum(self, u):
		sm = 0
		while u > 0:
			sm += self.fw[u]
			u -= u & -u
		return sm
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	ppl = list(((a, i) for (i, a) in enumerate(map(int, input().split()))))
	bd = [[] for _ in range(n)]
	for (i, (a, p)) in enumerate(sorted(ppl)):
		bd[i // m].append((a, -p))
		if i % m == m - 1:
			bd[i // m].sort()
	(fw, cc) = (fenwick(n * m), 0)
	for i in range(n):
		for j in range(m):
			p = -bd[i][j][1] + 1
			cc += fw.psum(p)
			fw.add(p, 1)
		for j in range(m):
			p = -bd[i][j][1] + 1
			fw.add(p, -1)
	print(cc)


from sys import stdin, stdout

def INPUT():
	return list((int(i) for i in stdin.readline().split()))

def inp():
	return stdin.readline()

def out(x):
	return stdout.write(x)
from math import *
from decimal import *
INT_MAX = 10 ** 13
mod = 998244353

def ceil(a, b):
	return (a + b - 1) // b

def pow(a, n):
	res = 1
	while n:
		if n & 1:
			res = res * a % mod
		a = a * a
		a %= mod
		n >>= 1
	return res

def count(A, s, e, ele):
	c = 0
	for i in range(s, e):
		if A[i] != 0 and A[i] != ele:
			c += 1
	return c
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = INPUT()
	C = A.copy()
	A.sort()
	B = [0] * n * m
	dicti = {}
	for i in range(n * m):
		if A[i] in dicti:
			dicti[A[i]][1] = i
		else:
			dicti[A[i]] = [i, i]
	ans = 0
	for i in range(n * m):
		B[dicti[C[i]][0]] = C[i]
		ans += count(B, dicti[C[i]][0] // m * m, dicti[C[i]][0], C[i])
		dicti[C[i]][0] += 1
	print(ans)


def inp():
	return int(input())

def st():
	return input().rstrip('\n')

def lis():
	return list(map(int, input().split()))

def ma():
	return map(int, input().split())
t = inp()
while t:
	t -= 1
	(n, m) = ma()
	a = lis()
	b = sorted(a)
	r = []
	dic = {}
	cc = 0
	row = [[-1 for i in range(m)] for j in range(n)]
	for i in range(n):
		for j in range(m):
			row[i][j] = b[cc]
			cc += 1
	ind = {}
	for i in range(n * m):
		try:
			ind[a[i]].append(i)
		except:
			ind[a[i]] = [i]
	for i in ind.keys():
		ind[i] = ind[i][::-1]
		res = 0
	for i in range(n):
		lr = []
		for j in range(m):
			z = ind[row[i][j]].pop()
			lr.append([z, row[i][j]])
		lr.sort()
		for j in range(m):
			for k1 in range(j + 1, m):
				if lr[j][1] < lr[k1][1]:
					res += 1
	print(res)


from sys import stdin
input = stdin.readline
import math
import bisect
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	(ans, l, b) = (0, n * m, [])
	for i in range(l):
		b.append([a[i], i + 1])
	b.sort()
	for i in range(n):
		for j in range(m):
			for k in range(j):
				if b[i * m + j][0] > b[i * m + k][0] and b[i * m + j][1] > b[i * m + k][1]:
					ans += 1
	print(ans)


import bisect
import copy
import decimal
import fractions
import functools
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque, defaultdict
from functools import lru_cache, reduce
from heapq import heappush, heappop, heapify, heappushpop, _heappop_max, _heapify_max

def _heappush_max(heap, item):
	heap.append(item)
	heapq._siftdown_max(heap, 0, len(heap) - 1)

def _heappushpop_max(heap, item):
	if heap and item < heap[0]:
		(item, heap[0]) = (heap[0], item)
		heapq._siftup_max(heap, 0)
	return item
from math import degrees, gcd as GCD
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

class Segment_Tree:

	def __init__(self, N, f, e, lst=None):
		self.f = f
		self.e = e
		self.N = N
		if lst == None:
			self.segment_tree = [self.e] * 2 * self.N
		else:
			assert len(lst) <= self.N
			self.segment_tree = [self.e] * self.N + [x for x in lst] + [self.e] * (N - len(lst))
			for i in range(self.N - 1, 0, -1):
				self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

	def __getitem__(self, i):
		if type(i) == int:
			if -self.N <= i < 0:
				return self.segment_tree[i + self.N * 2]
			elif 0 <= i < self.N:
				return self.segment_tree[i + self.N]
			else:
				raise IndexError('list index out of range')
		else:
			(a, b, c) = (i.start, i.stop, i.step)
			if a == None or a < -self.N:
				a = self.N
			elif self.N <= a:
				a = self.N * 2
			elif a < 0:
				a += self.N * 2
			else:
				a += self.N
			if b == None or self.N <= b:
				b = self.N * 2
			elif b < -self.N:
				b = self.N
			elif b < 0:
				b += self.N * 2
			else:
				b += self.N
			return self.segment_tree[slice(a, b, c)]

	def __setitem__(self, i, x):
		if -self.N <= i < 0:
			i += self.N * 2
		elif 0 <= i < self.N:
			i += self.N
		else:
			raise IndexError('list index out of range')
		self.segment_tree[i] = x
		while i > 1:
			i >>= 1
			self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

	def Build(self, lst):
		for (i, x) in enumerate(lst, self.N):
			self.segment_tree[i] = x
		for i in range(self.N - 1, 0, -1):
			self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

	def Fold(self, L=None, R=None):
		if L == None or L < -self.N:
			L = self.N
		elif self.N <= L:
			L = self.N * 2
		elif L < 0:
			L += self.N * 2
		else:
			L += self.N
		if R == None or self.N <= R:
			R = self.N * 2
		elif R < -self.N:
			R = self.N
		elif R < 0:
			R += self.N * 2
		else:
			R += self.N
		vL = self.e
		vR = self.e
		while L < R:
			if L & 1:
				vL = self.f(vL, self.segment_tree[L])
				L += 1
			if R & 1:
				R -= 1
				vR = self.f(self.segment_tree[R], vR)
			L >>= 1
			R >>= 1
		return self.f(vL, vR)

	def Fold_Index(self, L=None, R=None):
		if L == None or L < -self.N:
			L = self.N
		elif self.N <= L:
			L = self.N * 2
		elif L < 0:
			L += self.N * 2
		else:
			L += self.N
		if R == None or self.N <= R:
			R = self.N * 2
		elif R < -self.N:
			R = self.N
		elif R < 0:
			R += self.N * 2
		else:
			R += self.N
		if L == R:
			return None
		x = self.Fold(L - self.N, R - self.N)
		while L < R:
			if L & 1:
				if self.segment_tree[L] == x:
					i = L
					break
				L += 1
			if R & 1:
				R -= 1
				if self.segment_tree[R] == x:
					i = R
					break
			L >>= 1
			R >>= 1
		while i < self.N:
			if self.segment_tree[i] == self.segment_tree[i << 1]:
				i <<= 1
			else:
				i <<= 1
				i |= 1
		i -= self.N
		return i

	def __str__(self):
		return '[' + ', '.join(map(str, self.segment_tree[self.N:])) + ']'
T = int(readline())
for t in range(T):
	(N, M) = map(int, readline().split())
	A = list(map(int, readline().split()))
	sorted_A = sorted(A)
	(L, R) = ({}, {})
	L[sorted_A[0]] = 0
	R[sorted_A[N * M - 1]] = N * M
	for i in range(1, N * M):
		if sorted_A[i - 1] != sorted_A[i]:
			R[sorted_A[i - 1]] = i
			L[sorted_A[i]] = i
	dct = defaultdict(list)
	for a in L.keys():
		for i in range(L[a], R[a]):
			dct[a].append(i)
		dct[a].sort(reverse=True, key=lambda i: (i // M, -(i % M)))
	ST = [Segment_Tree(M, lambda x, y: x + y, 0) for i in range(N)]
	ans = 0
	for a in A:
		i = dct[a].pop()
		(n, m) = divmod(i, M)
		ans += ST[n].Fold(L=None, R=m)
		ST[n][m] += 1
	print(ans)


import bisect
import collections
import copy
import enum
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List

class TreeArray:

	def __init__(self, n: int):
		self.n = n
		self.arr = [0] * n

	def lowbit(self, x):
		return x & -x

	def update(self, x, y):
		i = x
		while i < self.n:
			self.arr[i] += y
			i += self.lowbit(i)

	def sum(self, x):
		ans = 0
		i = x
		while i > 0:
			ans += self.arr[i]
			i -= self.lowbit(i)
		return ans
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ts = [TreeArray(m + 2) for _ in range(n)]
	ans = 0
	cs = list(map(int, input().split()))
	cs2 = [[i, c] for (i, c) in enumerate(cs)]
	cs2.sort(key=lambda x: x[1])
	mp = collections.defaultdict(lambda : collections.defaultdict(int))
	mpc = collections.defaultdict(list)
	for r in range(n):
		for j in range(m):
			idx = r * m + j
			mp[cs2[idx][1]].setdefault(r, j + 1)
			mpc[cs2[idx][1]].append(r)
	for mc in cs:
		r = mpc[mc].pop(0)
		c = mp[mc][r]
		ans += ts[r].sum(c - 1)
		ts[r].update(c, 1)
	print(ans)


from heapq import heapify, heappop, heappush
from collections import deque
t = int(input())
for xx in range(t):
	[n, m] = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	na = []
	for i in range(len(a)):
		na.append((a[i], -1 * (i + 1)))
	na.sort()
	seats = []
	for i in range(n):
		v = []
		for j in range(m):
			v.append(-1)
		seats.append(v)

	def allocate():
		myList = []
		myList.append((na[0][0], deque([-1 * na[0][1]])))
		for i in range(1, len(na)):
			if myList[-1][0] == na[i][0]:
				myList[-1][1].append(-1 * na[i][1])
			else:
				myList.append((na[i][0], deque([-1 * na[i][1]])))
		myList.reverse()
		row = 0
		index = 0
		alloc = []
		inqu = 0
		while row < n:
			while inqu < m:
				alloc.append(myList.pop()[1])
				inqu += len(alloc[-1])
			alloc.reverse()
			seats_left = m
			col = 0
			while seats_left > 0:
				xyz = alloc.pop()
				if len(xyz) <= seats_left:
					lxyz = len(xyz)
					while len(xyz) > 0:
						seats[row][col] = xyz.popleft()
						col += 1
					seats_left -= lxyz
				else:
					col = m - 1
					while seats_left > 0:
						seats[row][col] = xyz.pop()
						seats_left -= 1
						col -= 1
					alloc.append(xyz)
			inqu -= m
			row += 1
	allocate()

	def mergeSort(s, l, r):
		if l >= r:
			return 0
		m = (l + r) // 2
		ca = mergeSort(s, l, m)
		cb = mergeSort(s, m + 1, r)
		a = s[l:m + 1]
		b = s[m + 1:r + 1]
		count = 0
		i = 0
		j = 0
		c = []
		while i < len(a) and j < len(b):
			if a[i] <= b[j]:
				c.append(a[i])
				i += 1
				count += j
			else:
				c.append(b[j])
				j += 1
		while i < len(a):
			c.append(a[i])
			i += 1
			count += j
		while j < len(b):
			c.append(b[j])
			j += 1
		s[l:r + 1] = c
		return ca + cb + count

	def helper():
		count = 0
		for s in seats:
			s.reverse()
			count += mergeSort(s, 0, len(s) - 1)
		return count
	print(helper())


import sys
for _ in range(int(sys.stdin.readline())):
	(n, m) = [int(_) for _ in sys.stdin.readline().split()]
	s = [int(_) for _ in sys.stdin.readline().split()]
	s = sorted([*zip(s, list(range(1, n * m + 1)))])
	r = 0
	for i in range(n):
		x = sorted(s[i * m:(i + 1) * m], key=lambda x: (x[0], -x[1]))
		for j in range(m):
			for k in range(j):
				r += x[j][1] > x[k][1]
	sys.stdout.write('%d\n' % r)


T = int(input())
from collections import defaultdict
from bisect import *
import heapq

def solve():
	(m, n) = map(int, input().split())
	arr = [int(x) for x in input().split()]
	d = defaultdict(list)
	for (i, a) in enumerate(sorted(arr)):
		heapq.heappush(d[a], (i // n, -i))
	sits = [[] for _ in range(m)]
	ans = 0
	for a in arr:
		(vs, index) = heapq.heappop(d[a])
		index = -index
		ans += bisect_left(sits[index // n], index % n)
		insort(sits[index // n], index % n)
	print(ans)
for _ in range(T):
	solve()


import math
import heapq
import string
from collections import deque
from bisect import bisect, bisect_left, bisect_right, insort
import sys
input = sys.stdin.readline
S = lambda : input().rstrip()
I = lambda : int(S())
M = lambda : map(int, S().split())
L = lambda : list(M())
H = 1000000000 + 7
for _ in range(I()):
	(n, m) = M()
	l = L()
	a = list(enumerate(l))
	a.sort(key=lambda x: x[1])
	c = 0
	for i in range(0, n * m, m):
		for j in range(i, i + m):
			for k in range(i, j):
				if a[k][0] < a[j][0] and a[k][1] < a[j][1]:
					c += 1
	print(c)


import sys
input = sys.stdin.readline
import copy

def moving(n, m, cu, num):
	cur = copy.copy(cu)
	cur[1] += num
	if cur[1] >= m:
		cur[0] += cur[1] // m
		cur[1] = cur[1] % m
	return [cur[0], cur[1]]
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	la = list(map(int, input().split()))
	la2 = copy.copy(la)
	la2 = list(set(la2))
	la2.sort()
	dicl = dict([])
	for i in range(len(la2)):
		dicl[la2[i]] = i
	alist = [[] for _ in range(n * m)]
	for i in range(n * m):
		alist[dicl[la[i]]].append(i)
	seat = [[0 for _ in range(m)] for _ in range(n)]
	revseat = [(0, 0)] * (n * m)
	cur = [0, 0]
	for w in alist:
		if len(w) == 0:
			break
		elif cur[1] + len(w) >= m:
			w2 = copy.copy(w)
			while cur[1] + len(w2) >= m:
				bef = w2[:m - cur[1]]
				af = w2[m - cur[1]:]
				while bef:
					revseat[bef.pop()] = cur
					cur = moving(n, m, cur, 1)
				w2 = af
			bef = w2[:m - cur[1]]
			af = w2[m - cur[1]:]
			while bef:
				revseat[bef.pop()] = cur
				cur = moving(n, m, cur, 1)
		else:
			w2 = copy.copy(w)
			while w2:
				revseat[w2.pop()] = cur
				cur = moving(n, m, cur, 1)
	ans = 0
	for i in range(n * m):
		ans += sum(seat[revseat[i][0]][:revseat[i][1]])
		seat[revseat[i][0]][revseat[i][1]] = 1
	print(ans)


from collections import Counter

def il():
	return list(map(int, input().split()))

def ii():
	return int(input())

def imi():
	return map(int, input().split())
t = ii()
for _ in range(t):
	(n, m) = imi()
	ar = il()
	nm = n * m
	li = []
	for i in range(nm):
		li.append([ar[i], i])
	li.sort()
	sr = 0
	s = 0
	for r in range(n):
		for i in range(sr, sr + m):
			x = li[i][0]
			ix = li[i][1]
			for j in range(sr, i):
				if li[j][0] < x and li[j][1] < ix:
					s += 1
		sr += m
	print(s)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
from math import ceil, floor, sqrt, log2, gcd, pi
from heapq import heappush, heappop
from bisect import bisect_left, bisect
import sys
abc = 'abcdefghijklmnopqrstuvwxyz'
ABC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	arr = []
	for i in range(n * m):
		arr.append((a[i], i))
	arr.sort()
	ans = 0
	for i in range(n):
		temp = arr[i * m:i * m + m]
		temp.sort(key=lambda x: x[1])
		for j in range(m):
			for k in range(j):
				if temp[j][0] > temp[k][0]:
					ans += 1
	print(ans)


import sys
input = iter(sys.stdin.read().splitlines()).__next__

def solve():
	(n, m) = map(int, input().split())
	sights = {}
	for (i, sight) in enumerate(map(int, input().split())):
		if sight not in sights:
			sights[sight] = []
		sights[sight].append(i)
	seating = [None] * (n * m)
	current_row = 0
	current_col = 0
	for sight in sorted(sights):
		i = 0
		while current_col + len(sights[sight]) - i > m:
			for person in reversed(sights[sight][i:i + m - current_col]):
				seating[person] = (current_row, current_col)
				current_col += 1
				i += 1
			current_col = 0
			current_row += 1
		for person in reversed(sights[sight][i:]):
			seating[person] = (current_row, current_col)
			current_col += 1
	inconvenience = 0
	occupied = [[False] * m for _ in range(n)]
	for i in range(n * m):
		row_occupied = occupied[seating[i][0]]
		for j in range(seating[i][1]):
			if row_occupied[j]:
				inconvenience += 1
		row_occupied[seating[i][1]] = True
	return inconvenience
t = int(input())
output = []
for _ in range(t):
	output.append(solve())
print(*output, sep='\n')


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
from math import inf, log2

class SegmentTree:

	def __init__(self, array, func=max):
		self.n = len(array)
		self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1
		self.func = func
		self.default = 0 if self.func != min else inf
		self.data = [self.default] * (2 * self.size)
		self.process(array)

	def process(self, array):
		self.data[self.size:self.size + self.n] = array
		for i in range(self.size - 1, -1, -1):
			self.data[i] = self.func(self.data[2 * i], self.data[2 * i + 1])

	def query(self, alpha, omega):
		if alpha > omega:
			return 0
		if alpha == omega:
			return self.data[alpha + self.size]
		res = self.default
		alpha += self.size
		omega += self.size + 1
		while alpha < omega:
			if alpha & 1:
				res = self.func(res, self.data[alpha])
				alpha += 1
			if omega & 1:
				omega -= 1
				res = self.func(res, self.data[omega])
			alpha >>= 1
			omega >>= 1
		return res

	def update(self, index, value):
		index += self.size
		self.data[index] = value
		index >>= 1
		while index:
			self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1])
			index >>= 1
for _ in range(int(input()) if True else 1):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	indexes = {}
	to_take = []
	st = SegmentTree([0] * (n * m), func=lambda a, b: a + b)
	for i in range(len(a)):
		if a[i] not in indexes:
			indexes[a[i]] = []
			to_take += [a[i]]
		indexes[a[i]] += [i]
	to_take = sorted(to_take)
	seat = [0] * (n * m)
	cur = 0
	row = 0
	ans = 0
	for x in to_take:
		indexes[x] = indexes[x][::-1]
		while indexes[x]:
			last = min((row + 1) * m - 1, cur + len(indexes[x]) - 1)
			while indexes[x] and cur < (row + 1) * m:
				seat[indexes[x].pop()] = last
				last -= 1
				cur += 1
			if cur == (row + 1) * m:
				row += 1
	for i in range(n * m):
		row = seat[i] // m
		ans += st.query(row * m, seat[i] - 1)
		st.update(seat[i], 1)
	print(ans)


def naiveSolve():
	return

def solve():
	return

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m) = readIntArr()
		eyesight = readIntArr()
		tu = [(sight, i) for (i, sight) in enumerate(eyesight)]
		tu.sort()
		ans = 0
		for row in range(n):
			left = row * m
			for col in range(m):
				pos = left + col
				for leftItem in range(left, pos):
					if tu[leftItem][0] < tu[pos][0] and tu[leftItem][1] < tu[pos][1]:
						ans += 1
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x):
	print('{}'.format(x))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
for _abc in range(1):
	main()


def divisors(M):
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	return d

def popcount(x):
	x = x - (x >> 1 & 1431655765)
	x = (x & 858993459) + (x >> 2 & 858993459)
	x = x + (x >> 4) & 252645135
	x = x + (x >> 8)
	x = x + (x >> 16)
	return x & 127

def eratosthenes(n):
	res = [0 for i in range(n + 1)]
	prime = set([])
	for i in range(2, n + 1):
		if not res[i]:
			prime.add(i)
			for j in range(1, n // i + 1):
				res[i * j] = 1
	return prime

def factorization(n):
	res = []
	for p in prime:
		if n % p == 0:
			while n % p == 0:
				n //= p
			res.append(p)
	if n != 1:
		res.append(n)
	return res

def euler_phi(n):
	res = n
	for x in range(2, n + 1):
		if x ** 2 > n:
			break
		if n % x == 0:
			res = res // x * (x - 1)
			while n % x == 0:
				n //= x
	if n != 1:
		res = res // n * (n - 1)
	return res

def ind(b, n):
	res = 0
	while n % b == 0:
		res += 1
		n //= b
	return res

def isPrimeMR(n):
	d = n - 1
	d = d // (d & -d)
	L = [2, 3, 5, 7, 11, 13, 17]
	for a in L:
		t = d
		y = pow(a, t, n)
		if y == 1:
			continue
		while y != n - 1:
			y = y * y % n
			if y == 1 or t == n - 1:
				return 0
			t <<= 1
	return 1

def findFactorRho(n):
	from math import gcd
	m = 1 << n.bit_length() // 8
	for c in range(1, 99):
		f = lambda x: (x * x + c) % n
		(y, r, q, g) = (2, 1, 1, 1)
		while g == 1:
			x = y
			for i in range(r):
				y = f(y)
			k = 0
			while k < r and g == 1:
				ys = y
				for i in range(min(m, r - k)):
					y = f(y)
					q = q * abs(x - y) % n
				g = gcd(q, n)
				k += m
			r <<= 1
		if g == n:
			g = 1
			while g == 1:
				ys = f(ys)
				g = gcd(abs(x - ys), n)
		if g < n:
			if isPrimeMR(g):
				return g
			elif isPrimeMR(n // g):
				return n // g
			return findFactorRho(g)

def primeFactor(n):
	i = 2
	ret = {}
	rhoFlg = 0
	while i * i <= n:
		k = 0
		while n % i == 0:
			n //= i
			k += 1
		if k:
			ret[i] = k
		i += 1 + i % 2
		if i == 101 and n >= 2 ** 20:
			while n > 1:
				if isPrimeMR(n):
					(ret[n], n) = (1, 1)
				else:
					rhoFlg = 1
					j = findFactorRho(n)
					k = 0
					while n % j == 0:
						n //= j
						k += 1
					ret[j] = k
	if n > 1:
		ret[n] = 1
	if rhoFlg:
		ret = {x: ret[x] for x in sorted(ret)}
	return ret

def divisors(n):
	res = [1]
	prime = primeFactor(n)
	for p in prime:
		newres = []
		for d in res:
			for j in range(prime[p] + 1):
				newres.append(d * p ** j)
		res = newres
	res.sort()
	return res

def xorfactorial(num):
	if num == 0:
		return 0
	elif num == 1:
		return 1
	elif num == 2:
		return 3
	elif num == 3:
		return 0
	else:
		x = baseorder(num)
		return 2 ** x * ((num - 2 ** x + 1) % 2) + function(num - 2 ** x)

def xorconv(n, X, Y):
	if n == 0:
		res = [X[0] * Y[0] % mod]
		return res
	x = [X[i] + X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	y = [Y[i] + Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	z = [X[i] - X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	w = [Y[i] - Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	res1 = xorconv(n - 1, x, y)
	res2 = xorconv(n - 1, z, w)
	former = [(res1[i] + res2[i]) * inv for i in range(2 ** (n - 1))]
	latter = [(res1[i] - res2[i]) * inv for i in range(2 ** (n - 1))]
	former = list(map(lambda x: x % mod, former))
	latter = list(map(lambda x: x % mod, latter))
	return former + latter

def merge_sort(A, B):
	(pos_A, pos_B) = (0, 0)
	(n, m) = (len(A), len(B))
	res = []
	while pos_A < n and pos_B < m:
		(a, b) = (A[pos_A], B[pos_B])
		if a < b:
			res.append(a)
			pos_A += 1
		else:
			res.append(b)
			pos_B += 1
	res += A[pos_A:]
	res += B[pos_B:]
	return res

class UnionFindVerSize:

	def __init__(self, N):
		self._parent = [n for n in range(0, N)]
		self._size = [1] * N
		self.group = N

	def find_root(self, x):
		if self._parent[x] == x:
			return x
		self._parent[x] = self.find_root(self._parent[x])
		stack = [x]
		while self._parent[stack[-1]] != stack[-1]:
			stack.append(self._parent[stack[-1]])
		for v in stack:
			self._parent[v] = stack[-1]
		return self._parent[x]

	def unite(self, x, y):
		gx = self.find_root(x)
		gy = self.find_root(y)
		if gx == gy:
			return
		self.group -= 1
		if self._size[gx] < self._size[gy]:
			self._parent[gx] = gy
			self._size[gy] += self._size[gx]
		else:
			self._parent[gy] = gx
			self._size[gx] += self._size[gy]

	def get_size(self, x):
		return self._size[self.find_root(x)]

	def is_same_group(self, x, y):
		return self.find_root(x) == self.find_root(y)

class WeightedUnionFind:

	def __init__(self, N):
		self.parent = [i for i in range(N)]
		self.size = [1 for i in range(N)]
		self.val = [0 for i in range(N)]
		self.flag = True
		self.edge = [[] for i in range(N)]

	def dfs(self, v, pv):
		stack = [(v, pv)]
		new_parent = self.parent[pv]
		while stack:
			(v, pv) = stack.pop()
			self.parent[v] = new_parent
			for (nv, w) in self.edge[v]:
				if nv != pv:
					self.val[nv] = self.val[v] + w
					stack.append((nv, v))

	def unite(self, x, y, w):
		if not self.flag:
			return
		if self.parent[x] == self.parent[y]:
			self.flag = self.val[x] - self.val[y] == w
			return
		if self.size[self.parent[x]] > self.size[self.parent[y]]:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[x] += self.size[y]
			self.val[y] = self.val[x] - w
			self.dfs(y, x)
		else:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[y] += self.size[x]
			self.val[x] = self.val[y] + w
			self.dfs(x, y)

class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add_edge(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					heapq.heappush(que, (d[e.to], e.to))
		return d

def Z_algorithm(s):
	N = len(s)
	Z_alg = [0] * N
	Z_alg[0] = N
	i = 1
	j = 0
	while i < N:
		while i + j < N and s[j] == s[i + j]:
			j += 1
		Z_alg[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < N and k + Z_alg[k] < j:
			Z_alg[i + k] = Z_alg[k]
			k += 1
		i += k
		j -= k
	return Z_alg

class BIT:

	def __init__(self, n, mod=0):
		self.BIT = [0] * (n + 1)
		self.num = n
		self.mod = mod

	def query(self, idx):
		res_sum = 0
		mod = self.mod
		while idx > 0:
			res_sum += self.BIT[idx]
			if mod:
				res_sum %= mod
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		mod = self.mod
		while idx <= self.num:
			self.BIT[idx] += x
			if mod:
				self.BIT[idx] %= mod
			idx += idx & -idx
		return

class dancinglink:

	def __init__(self, n, debug=False):
		self.n = n
		self.debug = debug
		self._left = [i - 1 for i in range(n)]
		self._right = [i + 1 for i in range(n)]
		self.exist = [True for i in range(n)]

	def pop(self, k):
		if self.debug:
			assert self.exist[k]
		L = self._left[k]
		R = self._right[k]
		if L != -1:
			if R != self.n:
				(self._right[L], self._left[R]) = (R, L)
			else:
				self._right[L] = self.n
		elif R != self.n:
			self._left[R] = -1
		self.exist[k] = False

	def left(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._left[res]
			if res == -1:
				break
			k -= 1
		return res

	def right(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._right[res]
			if res == self.n:
				break
			k -= 1
		return res

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		n = N.bit_length()
		self.table = [[ide_ele for i in range(n)] for i in range(N)]
		self.merge_func = merge_func
		for i in range(N):
			self.table[i][0] = A[i]
		for j in range(1, n):
			for i in range(0, N - 2 ** j + 1):
				f = self.table[i][j - 1]
				s = self.table[i + 2 ** (j - 1)][j - 1]
				self.table[i][j] = self.merge_func(f, s)

	def query(self, s, t):
		b = t - s + 1
		m = b.bit_length() - 1
		return self.merge_func(self.table[s][m], self.table[t - 2 ** m + 1][m])

class BinaryTrie:

	class node:

		def __init__(self, val):
			self.left = None
			self.right = None
			self.max = val

	def __init__(self):
		self.root = self.node(-10 ** 15)

	def append(self, key, val):
		pos = self.root
		for i in range(29, -1, -1):
			pos.max = max(pos.max, val)
			if key >> i & 1:
				if pos.right is None:
					pos.right = self.node(val)
					pos = pos.right
				else:
					pos = pos.right
			elif pos.left is None:
				pos.left = self.node(val)
				pos = pos.left
			else:
				pos = pos.left
		pos.max = max(pos.max, val)

	def search(self, M, xor):
		res = -10 ** 15
		pos = self.root
		for i in range(29, -1, -1):
			if pos is None:
				break
			if M >> i & 1:
				if xor >> i & 1:
					if pos.right:
						res = max(res, pos.right.max)
					pos = pos.left
				else:
					if pos.left:
						res = max(res, pos.left.max)
					pos = pos.right
			elif xor >> i & 1:
				pos = pos.right
			else:
				pos = pos.left
		if pos:
			res = max(res, pos.max)
		return res

def solveequation(edge, ans, n, m):
	x = [0] * m
	used = [False] * n
	for v in range(n):
		if used[v]:
			continue
		y = dfs(v)
		if y != 0:
			return False
	return x

	def dfs(v):
		used[v] = True
		r = ans[v]
		for (to, dire, id) in edge[v]:
			if used[to]:
				continue
			y = dfs(to)
			if dire == -1:
				x[id] = y
			else:
				x[id] = -y
			r += y
		return r

class SegmentTree:

	def __init__(self, init_val, segfunc, ide_ele):
		n = len(init_val)
		self.segfunc = segfunc
		self.ide_ele = ide_ele
		self.num = 1 << (n - 1).bit_length()
		self.tree = [ide_ele] * 2 * self.num
		self.size = n
		for i in range(n):
			self.tree[self.num + i] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.tree[k] = x
		while k > 1:
			self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
			k >>= 1

	def query(self, l, r):
		if r == self.size:
			r = self.num
		res = self.ide_ele
		l += self.num
		r += self.num
		while l < r:
			if l & 1:
				res = self.segfunc(res, self.tree[l])
				l += 1
			if r & 1:
				res = self.segfunc(res, self.tree[r - 1])
			l >>= 1
			r >>= 1
		return res

	def bisect_l(self, l, r, x):
		l += self.num
		r += self.num
		Lmin = -1
		Rmin = -1
		while l < r:
			if l & 1:
				if self.tree[l] <= x and Lmin == -1:
					Lmin = l
				l += 1
			if r & 1:
				if self.tree[r - 1] <= x:
					Rmin = r - 1
			l >>= 1
			r >>= 1
		if Lmin != -1:
			pos = Lmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		elif Rmin != -1:
			pos = Rmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		else:
			return -1
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import gcd, log
input = lambda : sys.stdin.readline().rstrip()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
for _ in range(int(input())):
	(N, M) = mi()
	A = li()
	comp = {e: i for (i, e) in enumerate(sorted(set(A)))}
	n = len(comp)
	idx = [[] for i in range(n)]
	for i in range(N * M):
		g = comp[A[i]]
		idx[g].append(i)
	for i in range(n):
		idx[i] = idx[i][::-1]
	res = [[] for i in range(N)]
	now = 0
	for i in range(n):
		if M - len(res[now]) >= len(idx[i]):
			res[now] += idx[i]
			if len(res[now]) == M:
				now += 1
		else:
			fill = M - len(res[now])
			cnt = len(idx[i])
			res[now] += idx[i][cnt - fill:cnt]
			idx[i] = idx[i][:cnt - fill]
			now += 1
			while len(idx[i]) > M:
				cnt = len(idx[i])
				res[now] += idx[i][cnt - M:cnt]
				idx[i] = idx[i][:cnt - M]
				now += 1
			res[now] += idx[i]
			if len(res[now]) == M:
				now += 1
	fw = BIT(N * M)
	ans = 0
	for i in range(N):
		for j in res[i]:
			ans += fw.query(j)
			fw.update(j + 1, 1)
		for j in res[i]:
			fw.update(j + 1, -1)
	print(ans)


import math
import os
import sys
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
import random
M = 10 ** 9 + 7
import heapq
import bisect
from functools import lru_cache
from queue import PriorityQueue
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def sumofdigits(n):
	n = str(n)
	s1 = 0
	for i in n:
		s1 += int(i)
	return s1

def perfect_square(n):
	s = math.sqrt(n)
	if s == int(s):
		return True
	return False

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def query1(l, r):
	if l >= r:
		return -1
	print('?', l + 1, r + 1)
	sys.stdout.flush()
	return int(input()) - 1

def answer(p):
	print('!', p + 1)
	sys.stdout.flush()
	exit()

def rse(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(n)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(n)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def lse(arr, n):
	stack = []
	ans = []
	for i in range(n):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	return ans

def mah(arr):
	max1 = 0
	p = rse(arr, len(arr))
	q = lse(arr, len(arr))
	for i in range(len(arr)):
		a = (p[i] - q[i] - 1) * arr[i]
		max1 = max(a, max1)
	return max1

def maxSumIS(arr, n):
	msis = arr.copy()
	for i in range(1, n):
		for j in range(i):
			if arr[i] > arr[j] and msis[i] < msis[j] + arr[i]:
				msis[i] = msis[j] + arr[i]
	c = max(msis)
	p = 5
	return c

def binarysearch2(arr, target):
	lo = 0
	hi = len(arr) - 1
	while lo <= hi:
		mid = (lo + hi) // 2
		if arr[mid] == target:
			if mid != len(arr) - 1:
				if arr[mid + 1] != target:
					return mid
				else:
					lo += 1
			else:
				return mid
			continue
		if arr[mid] > target:
			hi = mid - 1
		else:
			lo = mid + 1

def nge(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) > 0:
				if stack[-1][0] < arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def alperm(nums, path, result):
	if not nums:
		result.add(tuple(path))
		return
	for i in range(0, len(nums)):
		alperm(nums[:i] + nums[i + 1:], path + [nums[i]], result)
	return result

def minsum(arr, n, m, res, l):
	if n == 1 and m == 1:
		res += arr[0][0]
		l.append(res)
	else:
		if n != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n - 1, m, p, l)
		if m != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n, m - 1, p, l)
	return min(l)

def find_shortest_path(graph, start, end, path):
	path = path + [start]
	if start == end:
		return path
	if start not in graph:
		return None
	shortest = None
	for node in graph[start]:
		if node not in path:
			newpath = find_shortest_path(graph, node, end, path)
			if newpath:
				if not shortest or len(newpath) < len(shortest):
					shortest = newpath
	return shortest

def test(n, d):
	a = random.randint(1, n - 2)
	p = pow(a, d, n)
	if p == 1 or p == n - 1:
		return True
	while d != n - 1:
		d *= 2
		p = pow(p, 2, n)
		if p == n - 1:
			return True
	return False

def isprime(n):
	if n == 1:
		return False
	if n == 2:
		return True
	if n == 3:
		return True
	d = n - 1
	while d % 2 == 0:
		d //= 2
	for i in range(5):
		if test(n, d) == False:
			return False
	return True

def muin(a, m):
	(x, y, mo) = (1, 0, m)
	if m == 1:
		return 0
	while m > 0:
		(x, y) = (y, x - a // m * y)
		(a, m) = (m, a % m)
	if x < 0:
		return mo + x
	else:
		return x

def facto(fact):
	(fact[0], fact[1]) = (1, 1)
	for i in range(2, 10 ** 6 + 1):
		fact[i] = fact[i - 1] * i % M

def comb(n, r, fact):
	return fact[n] * pow(fact[n - r] * fact[r], M - 2, M) % M

def numberToBase(n, b):
	if n == 0:
		return 0
	digits = []
	while n:
		digits.append(n % b)
		n //= b
	return sum(digits)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		(n, m) = sep()
		s = lis()
		order = sorted(zip(s, list(range(1, n * m + 1))))
		count = 0
		for (j, person) in enumerate(order):
			row = j - j % m
			for k in range(j + 1, row + m):
				person2 = order[k]
				if person2[1] > person[1]:
					if person2[0] != person[0]:
						count += 1
		print(count)
main()


import sys
import os
import math
from io import BytesIO, IOBase
from collections import defaultdict, Counter, deque
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def getsum(BIT, i):
	s = 0
	i += 1
	while i > 0:
		s += BIT[i]
		i -= i & -i
	return s

def updatebit(BIT, n, i, v):
	i += 1
	while i <= n:
		BIT[i] += v
		i += i & -i
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = defaultdict(list)
	for j in range(n * m):
		c[a[j]].append(j)
	c1 = 0
	ind = {}
	for j in sorted(c):
		start = -1
		while start != len(c[j]) - 1:
			ma = min(m - c1 % m, len(c[j]) - 1 - start)
			for k in range(start + ma, start, -1):
				ind[c[j][k]] = [c1 // m, c1 % m]
				c1 += 1
				start += 1
	ans = 0
	BIT = [[0] * (m + 1) for j in range(n)]
	for j in range(n * m):
		ans += getsum(BIT[ind[j][0]], ind[j][1])
		updatebit(BIT[ind[j][0]], m, ind[j][1], 1)
	print(ans)


import sys
read = lambda : sys.stdin.readline()
from bisect import bisect_left
from collections import defaultdict
for _ in range(int(read())):
	(n, m) = map(int, read().split())
	a = list(map(int, read().split()))
	khaali = [[] for i in range(n)]
	b = sorted(a)
	idx = defaultdict(lambda : [])
	for i in range(n * m):
		idx[b[i]].append(i // m)
	ans = 0
	for num in a:
		row = idx[num].pop(0)
		op = bisect_left(khaali[row], num)
		ans += op
		khaali[row].insert(op, num)
	print(ans)


import io, os
import bisect
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main(t):
	(m, n) = map(int, input().split())
	arr = list(map(int, input().split()))
	temp = []
	for index in range(m * n):
		temp.append([arr[index], index])
	temp = sorted(temp)
	dic = {}
	for index in range(m * n):
		if temp[index][0] not in dic:
			dic[temp[index][0]] = []
		dic[temp[index][0]].append([-(index // n), index % n])
	for key in dic:
		dic[key] = sorted(dic[key])
	seated = [[] for _ in range(m)]
	ans = 0
	for index in range(m * n):
		[row, col] = dic[arr[index]].pop()
		row = -row
		loc = bisect.bisect(seated[row], col)
		ans += loc
		bisect.insort(seated[row], col)
	print(ans)
T = int(input())
t = 1
while t <= T:
	main(t)
	t += 1


def pos(sa, k, l=0, r=None):
	if r is None:
		r = len(sa)
	m = (l + r) // 2
	if l == r:
		return l
	elif k > sa[m]:
		return pos(sa, k, m + 1, r)
	elif k < sa[m]:
		return pos(sa, k, l, m)
	else:
		return m

def val(q):
	inc = 0
	slist = []
	for i in q:
		if not slist:
			slist.append(i)
		else:
			p = pos(slist, i)
			inc += p
			slist.insert(p, i)
	return inc
t = int(input())
for _ in range(t):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	sights = sorted(list(set(a)))
	bins = {i: [] for i in sights}
	for i in range(len(a)):
		bins[a[i]].append(i)
	total_inc = 0
	row = []
	for i in sights:
		b = bins[i]
		z = 0
		while z < len(b):
			if len(row) + len(b) - z < m:
				row += b[z:][::-1]
				z = len(b)
			else:
				fz = z + m - len(row)
				addition = b[z:fz][::-1]
				row += addition
				total_inc += val(row)
				row = []
				z = fz
	print(total_inc)


def solve(n, m, sight):
	sight_i = [(-sight[i], i + 1) for i in range(len(sight))]
	sight_i.sort(reverse=True)
	last_change = 0
	last_x = sight_i[0][0]
	new_order = []
	tmp = []
	for (i, x) in enumerate(sight_i):
		(s, id) = x
		if s != last_x:
			new_order = add_sights(last_change, m, new_order, tmp)
			last_change = i
			tmp = []
		last_x = s
		tmp.append((s, id))
	last_change = add_sights(last_change, m, new_order, tmp)
	order = [(j, new_order[j][1]) for j in range(len(sight))]
	tot = 0
	for (index, i) in order:
		count = 0
		for k in range(1, m):
			if (index + k) % m <= index % m:
				break
			if order[index + k][1] > i:
				count += 1
		tot += count
	return tot

def add_sights(last_change, m, new_order, tmp):
	if last_change % m + len(tmp) < m:
		new_order += tmp
		return new_order
	first_split = m - last_change % m
	new_order += tmp[-first_split:]
	tmp = tmp[:-first_split]
	if len(tmp) > m:
		take_first = tmp[:len(tmp) % m]
		tmp = tmp[len(tmp) % m:]
		new_order += tmp
		new_order += take_first
	else:
		new_order += tmp
	return new_order
import os
import io
import time
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input().decode().strip())
for t in range(T):
	(n, m) = [int(x) for x in input().decode().strip().split(' ')]
	sight = [int(x) for x in input().decode().strip().split(' ')]
	res = solve(n, m, sight)
	print(res)


def naiveSolve():
	return

def solve():
	return

class SegmentTree:

	def __init__(self, arr, combinerFunction, isCommutative=True):
		self.n = len(arr)

		def cmb(a, b):
			if a == None:
				return b
			if b == None:
				return a
			return combinerFunction(a, b)
		self.cmb = cmb
		self.sz = self.n if isCommutative else pow(2, (self.n - 1).bit_length())
		self.t = [None] * (2 * self.sz)
		for i in range(self.n):
			self.t[i + self.sz] = arr[i]
		for i in range(self.sz - 1, 0, -1):
			self.pull(i)

	def pull(self, p):
		self.t[p] = self.cmb(self.t[2 * p], self.t[2 * p + 1])

	def update(self, idx, val):
		idx += self.sz
		self.t[idx] = val
		idx //= 2
		while idx > 0:
			self.pull(idx)
			idx //= 2

	def query(self, l, r):
		l += self.sz
		r += self.sz + 1
		a = b = None
		while l < r:
			if l % 2 == 1:
				a = self.cmb(a, self.t[l])
				l += 1
			if r % 2 == 1:
				r -= 1
				b = self.cmb(self.t[r], b)
			l //= 2
			r //= 2
		return self.cmb(a, b)

def getMaxSegTree(arr):
	return SegmentTree(arr, lambda a, b: max(a, b), False)

def getMinSegTree(arr):
	return SegmentTree(arr, lambda a, b: min(a, b), False)

def getSumSegTree(arr):
	return SegmentTree(arr, lambda a, b: a + b, False)
from collections import defaultdict

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m) = readIntArr()
		eyesight = readIntArr()
		tu = [(sight, i) for (i, sight) in enumerate(eyesight)]
		tu.sort()
		sightSeats = defaultdict(lambda : [])
		sightIndexes = defaultdict(lambda : [])
		for (seat, (sight, i)) in enumerate(tu):
			sightSeats[sight].append(seat)
			sightIndexes[sight].append(i)
		seating = [-1] * (m * n)
		for (sight, seats) in sightSeats.items():
			indexes = sorted(sightIndexes[sight])
			rowSeats = defaultdict(lambda : [])
			for seat in seats:
				(row, col) = divmod(seat, m)
				rowSeats[row].append((col, seat))
			rows = sorted(rowSeats.keys())
			j = 0
			for row in rows:
				rowSeats[row].sort(reverse=True)
				for (col, seat) in rowSeats[row]:
					seating[indexes[j]] = seat
					j += 1
		ans = 0
		rowCnts = [getSumSegTree([0] * m) for __ in range(n)]
		for i in range(n * m):
			seat = seating[i]
			(row, col) = divmod(seat, m)
			ans += rowCnts[row].query(0, col)
			rowCnts[row].update(col, 1)
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x):
	print('{}'.format(x))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
for _abc in range(1):
	main()


import bisect

def solve(sights, m, n):
	L = sorted(range(m * n), key=lambda i: sights[i])
	ans = 0
	for r in range(m):
		row = L[r * n:(r + 1) * n]
		row.sort(key=lambda i: (sights[i], -i))
		seen = []
		for x in row:
			i = bisect.bisect_left(seen, x)
			ans += i
			seen.insert(i, x)
	return ans
for _ in range(int(input())):
	(m, n) = map(int, input().split())
	sights = list(map(int, input().split()))
	print(solve(sights, m, n))


from collections import Counter
from sys import stdin, gettrace
if gettrace():

	def inputi():
		return input()
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	(n, m) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	order = sorted(range(len(aa)), key=aa.__getitem__)
	row = [-1] * n * m
	for (i, o) in enumerate(order):
		row[o] = i // m
	aac = [Counter() for _ in range(n)]
	res = 0
	for (i, a) in enumerate(aa):
		res += sum((aac[row[i]][j] for j in aac[row[i]] if j < a))
		aac[row[i]][a] += 1
	print(res)

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


import sys
pin = sys.stdin.readline

def update(tree, n):
	while n < len(tree):
		tree[n] += 1
		n += n & -n

def psum(tree, n):
	ans = 0
	while n:
		ans += tree[n]
		n -= n & -n
	return ans
for T in range(int(pin())):
	(N, M) = map(int, pin().split())
	A = sorted([(v, k) for (k, v) in enumerate([*map(int, pin().split())])])
	A = sorted([(v[0], i // M, -v[1], -(i % M)) for (i, v) in enumerate(A)])
	A = sorted([(-v[2], v[1], i % M) for (i, v) in enumerate(A)])
	Tree = [[0] * (M + 1) for _ in range(N)]
	ans = 0
	for i in range(M * N):
		r = A[i][1]
		c = A[i][2]
		update(Tree[r], c + 1)
		ans += psum(Tree[r], c)
	print(ans)


import sys
import math
import random
import heapq
input = sys.stdin.readline

def pow(a, n, m):
	if n == 0:
		return 1
	x = pow(a, n // 2, m)
	if n % 2 == 0:
		return x * x % m
	else:
		return x * x * a % m

def gcd(a, b):
	while b != 0:
		(a, b) = (b, a % b)
	return a

def bs(arr, le, ri):
	l = 0
	arr.sort()
	r = len(arr) - 1
	ans = 10000000
	while l <= r:
		m = (l + r) // 2
		if arr[m] >= le and arr[m] <= ri:
			ans = arr[m]
			r = m - 1
		elif arr[m] < le:
			l = m + 1
		else:
			r = m - 1
	return ans
t = int(input())
while t > 0:
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	d = {}
	for i in l:
		d[i] = d.get(i, 0) + 1
	s = {}
	c = 0
	for i in sorted(d.keys()):
		s[i] = [c, c + d[i] - 1]
		c += d[i]
	ans = 0
	a = [[0 for i in range(m)] for j in range(n)]
	for i in range(n * m):
		x = l[i]
		if s[x][0] // m != s[x][1] // m:
			for j in range(s[x][0] % m):
				if a[s[x][0] // m][j] == 1:
					ans += 1
			s[x][0] += 1
		else:
			for j in range(s[x][0] % m):
				if a[s[x][0] // m][j] == 1:
					ans += 1
			a[s[x][0] // m][s[x][1] % m] = 1
			s[x][1] -= 1
	print(ans)
	t -= 1


from __future__ import division, print_function
import math
import sys
import os
from io import BytesIO, IOBase
from collections import deque, Counter, OrderedDict, defaultdict
from bisect import bisect_left, bisect_right
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def inp():
	return int(input())

def inps():
	return input().strip()

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
for _ in range(inp()):
	(n, m) = invr()
	l = inlt()
	ans = [[l[i], i] for i in range(n * m)]
	ans.sort()
	inconv = 0
	cnt = 0
	for i in range(n):
		lst = ans[i * m:i * m + m]
		lst.sort(key=lambda x: x[1])
		for i in range(m):
			for j in range(i):
				if lst[i][0] > lst[j][0]:
					cnt += 1
	print(cnt)


from io import BytesIO, IOBase
import sys
import math
import os
import heapq
from collections import defaultdict, deque
from math import ceil, log2
from bisect import bisect_left, bisect_right
from time import perf_counter
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def mint():
	return map(int, input().split())

def mfloat():
	return map(float, input().split())

def intin():
	return int(input())

class SegmentTree:

	def __init__(self, data):
		self.n = len(data)
		self.tree = [0] * (2 * self.n)
		for i in range(self.n, 2 * self.n):
			self.tree[i] = data[i - self.n]
		self.lazy = [0] * self.n
		if self.n == 0:
			self.h == 0
		else:
			self.h = int(log2(self.n)) + 1
		self.build()

	def build(self):
		for i in range(self.n - 1, 0, -1):
			self.tree[i] = self.tree[i << 1] + self.tree[i << 1 | 1]

	def modify(self, p, value):
		p += self.n
		self.tree[p] = value
		while p > 1:
			self.tree[p >> 1] = self.tree[p] + self.tree[p ^ 1]
			p >>= 1

	def query(self, l, r):
		res = 0
		l += self.n
		r += self.n
		while l < r:
			if l & 1:
				res += self.tree[l]
				l += 1
			if r & 1:
				r -= 1
				res += self.tree[r]
			l >>= 1
			r >>= 1
		return res

def solve():
	(n, m) = mint()
	(*a,) = mint()
	sa = sorted(a)
	last_positions = {i: deque() for i in set(a)}
	for i in range(m * n):
		element = sa[i]
		(x, y) = divmod(i, m)
		if y == m - 1 or sa[i] != sa[i + 1]:
			last_positions[element].append((x, y))
	ans = 0
	segTrees = [SegmentTree([1] * m) for i in range(n)]
	for i in a:
		(x, y) = last_positions[i][0]
		segTrees[x].modify(y, 0)
		if len(last_positions[i]) == 1:
			ans += segTrees[x].query(y + 1, m)
		if y == 0 or sa[x * m + y] != sa[x * m + y - 1]:
			last_positions[i].popleft()
		else:
			last_positions[i][0] = (x, y - 1)
	print(ans)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
start_time = perf_counter()
main()
print(perf_counter() - start_time, file=sys.stderr)


class segt:

	def __init__(self, n):
		self.bp = 1
		while self.bp < n:
			self.bp <<= 1
		self.heap = [0] * (2 * self.bp)

	def add(self, idx):
		idx += self.bp
		self.heap[idx] = 1
		while idx > 0:
			idx //= 2
			self.heap[idx] = self.heap[idx * 2] + self.heap[idx * 2 + 1]

	def q(self, l, r):
		l += self.bp
		r += self.bp
		ans = 0
		while r >= l:
			if l & 1:
				ans += self.heap[l]
				l += 1
			if not r & 1:
				ans += self.heap[r]
				r -= 1
			l //= 2
			r //= 2
		return ans
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	eyes = list(map(int, input().split()))
	e2 = [[eyes[i], i] for i in range(n * m)]
	e2 = sorted(e2, key=lambda x: (x[0], x[1]))
	cnt = dict()
	for el in e2:
		if el[0] in cnt:
			cnt[el[0]] += 1
		else:
			cnt[el[0]] = 1
	seats = [[0 for i in range(m)] for j in range(n)]
	rs = set()
	d = dict()
	ptr = 0
	for r in range(n):
		for c in range(m):
			el = e2[ptr]
			if not el[0] in rs:
				d[el[0]] = list()
			seats[r][c] = id
			rs.add(el[0])
			d[el[0]].append(ptr + 1)
			ptr += 1
	order = dict()
	for ky in d.keys():
		order[ky] = list()
		stop = 0
		for i in range(len(d[ky])):
			if d[ky][i] % m == 0 or i == len(d[ky]) - 1:
				for j in range(i, stop - 1, -1):
					order[ky].append(d[ky][j])
				stop = i + 1
	for ky in order.keys():
		order[ky].reverse()
	segts = dict()
	for i in range(n):
		segts[i] = segt(m)
	anse = 0
	for el in eyes:
		place = order[el].pop()
		q = (place - 1) // m
		anse += segts[q].q(0, (place - 1) % m)
		segts[q].add((place - 1) % m)
	print(anse)


from sys import stdin
input = stdin.readline
rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input().strip()
YN = lambda x: print('YES') if x else print('NO')
mod = 10 ** 9 + 7
from collections import defaultdict

class SegmentTree:

	def __init__(self, data, default=0, func=max):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
for _ in range(rn()):
	(n, m) = rns()
	a = rl()
	rows = [SegmentTree([0 for i in range(m)], func=lambda a, b: a + b) for j in range(n)]
	people = sorted(a)
	d = defaultdict(list)
	r = 0
	c = 0
	for i in range(n * m):
		d[people[i]].append((r, c))
		c += 1
		if c == m:
			c = 0
			r += 1
	for i in d:
		d[i].sort(key=lambda x: [-x[0], x[1]])
	ans = 0
	for num in a:
		coors = d[num].pop()
		ans += rows[coors[0]].query(0, coors[1])
		rows[coors[0]][coors[1]] = 1
	print(ans)


import sys, math
for _ in range(int(input())):
	(n, m) = [int(c) for c in input().split()]
	ans = 0
	origarr = [int(c) for c in input().split()]
	ar = [(origarr[i], i) for i in range(len(origarr))]
	ar.sort(key=lambda x: (x[0], x[1]))
	ar = [i for (j, i) in ar]
	finalarr = []
	for i in range(n):
		k = i * m
		finalarr.append(ar[k:k + m])
	for arr in finalarr:
		for i in range(len(arr)):
			for j in range(i + 1, len(arr)):
				if arr[j] > arr[i] and origarr[arr[i]] != origarr[arr[j]]:
					ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = tuple(map(int, input().split()))
	sp = input().split()
	sp = [(i, int(sp[i])) for i in range(n * m)]
	sp.sort(key=lambda x: (x[1], x[0]))
	new = []
	for i in range(0, n * m, m):
		new.append(sorted(sp[i:i + m], key=lambda x: (x[1], -1 * x[0])))
	ans = 0
	for e in new:
		for i in e:
			for j in e:
				if i[0] > j[0]:
					ans += 1
				elif i[0] == j[0]:
					break
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	a = sorted(((a[i], i) for i in range(len(a))))
	(r, d) = (0, 0)
	a.append((10 ** 9 + 9, -1))
	b = 0
	ca = []
	ans = []
	for i in range(n * m + 1):
		if a[b][0] != a[i][0]:
			rw = sorted(ca)
			nd = d + len(rw)
			if d - m >= i - b:
				rw = rw[::-1]
				ans.extend(rw)
			else:
				ans.extend(rw[m - d - 1::-1])
				rw = rw[m - d:]
				fd = len(rw) - len(rw) % m
				ans.extend(rw[:fd][::-1])
				rw = rw[fd:]
				ans.extend(rw[::-1])
			ca = []
			b = i
			r += nd // m
			d = nd % m
		ca.append(a[i][1])
	v = 0
	for i in range(0, n * m, m):
		for j in range(i, i + m):
			for k in range(j, i + m):
				v += ans[j] < ans[k]
	print(v)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	tot = n * m
	a = list(map(int, input().split()))
	l = list(range(tot))
	l.sort(key=lambda x: (a[x], x))
	mat = []
	for i in range(n):
		mat.append(l[m * i:m * (i + 1)])
	for i in range(n):
		mat[i].sort(key=lambda x: (a[x], -x))
	res = 0
	for i in range(n):
		cnt = 0
		for j in range(m):
			for k in range(j):
				cnt += mat[i][k] < mat[i][j]
		res += cnt
	print(res)


class BIT:

	def __init__(self, n):
		self.n = n
		self.data = [0] * n

	def build(self, arr):
		for (i, a) in enumerate(arr):
			self.data[i] = a
		for i in range(1, self.n + 1):
			if i + (i & -i) <= self.n:
				self.data[i + (i & -i) - 1] += self.data[i - 1]

	def add(self, p, x):
		p += 1
		while p <= self.n:
			self.data[p - 1] += x
			p += p & -p

	def sum(self, r):
		s = 0
		while r:
			s += self.data[r - 1]
			r -= r & -r
		return s

	def range_sum(self, l, r):
		return self.sum(r) - self.sum(l)

def solve():
	(n, m) = map(int, input().split())
	arr = list(zip(map(int, input().split()), range(n * m)))
	arr.sort()
	p = [0] * (n * m)
	i = 0
	while i < m * n:
		a = arr[i][0]
		j = i
		while j < m * n and arr[j][0] == a:
			j += 1
		L = [(k // m, -(k % m), k) for k in range(i, j)]
		L.sort()
		for k in range(i, j):
			p[arr[k][1]] = L[k - i][2]
		i = j
	v = BIT(n * m)
	ans = 0
	for (i, j) in enumerate(p):
		ans += v.range_sum(j // m * m, j)
		v.add(j, 1)
	return ans
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	print(solve())


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main():
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	people = [i + 1 for i in range(n * m)]
	zz = [(a[i], people[i]) for i in range(n * m)]
	dic = {}
	zz.sort(key=lambda k: (k[0], -k[1]))
	for i in range(n * m):
		if zz[i][0] in dic:
			dic[zz[i][0]].append(zz[i])
		else:
			dic[zz[i][0]] = [zz[i]]
	finale = []
	for i in range(n):
		pointer = 0
		x = 0
		for xs in list(dic):
			x += len(dic[xs])
			if x <= m:
				for i in range(len(dic[xs])):
					finale.append(dic[xs][i])
				dic.pop(xs)
			if x > m:
				for i in range(len(dic[xs]) - x + m):
					finale.append(dic[xs][i + x - m])
				dic[xs] = dic[xs][:x - m]
				break
	finale = [finale[i][1] for i in range(n * m)]
	sek = []
	sum = 0
	for i in range(n * m):
		if i % m == 0:
			sek = []
		pt = len(sek)
		for js in range(pt):
			if sek[js] < finale[i]:
				sum += 1
		sek.append(finale[i])
	print(sum)
for _ in range(int(input())):
	main()


import os, sys
from io import BytesIO, IOBase
from collections import *

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class dict(dict):

	def __missing__(self, key):
		return []

class segmenttree:

	def __init__(self, arr, n):
		(self.tree, self.n) = ([0] * (2 * n), n)

	def query(self, l, r):
		res = 0
		l += self.n
		r += self.n
		while l < r:
			if l & 1:
				res += self.tree[l]
				l += 1
			if r & 1:
				r -= 1
				res += self.tree[r]
			l >>= 1
			r >>= 1
		return res

	def update(self, ix, val):
		ix += self.n
		self.tree[ix] = val
		while ix > 1:
			self.tree[ix >> 1] = self.tree[ix] + self.tree[ix ^ 1]
			ix >>= 1
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp(dtype))]
inp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
for _ in range(int(input())):
	(n, m) = inp(int)
	(a, mem, ans) = (inp(int), defaultdict(lambda : deque([[]])), 0)
	(tem, seat) = (sorted(a.copy()), segmenttree([], n * m))
	for i in range(n * m):
		if i % m == 0:
			mem[tem[i]].append([])
		mem[tem[i]][-1].append(i)
	for i in range(n * m):
		while not mem[a[i]][0]:
			mem[a[i]].popleft()
		ix = mem[a[i]][0].pop()
		ans += seat.query(ix - ix % m, ix)
		seat.update(ix, 1)
	print(ans)


import sys
from collections import defaultdict
input = sys.stdin.readline

def cin_int():
	return int(input())

def cin_ls_int():
	return list(map(int, input().split()))

def cin_ls():
	return input().split()

def main():
	for _ in range(cin_int()):
		(n, m) = cin_ls_int()
		seats = cin_ls_int()
		memo = defaultdict(list)
		for (i, v) in enumerate(seats):
			memo[v].append(i)
		ls = list(memo.items())
		ls.sort()
		c = []
		for (_, v) in ls:
			c.extend(v)
		plan = [[0 for _ in range(m)] for _ in range(n)]
		for (i, v) in enumerate(c):
			plan[i // m][i % m] = v + 1
		idx = 0
		segment = len(ls[0][1])
		for row in plan:
			offset = 0
			while True:
				if segment == 0:
					idx += 1
					segment = len(ls[idx][1])
				if segment >= len(row) - offset:
					row[offset:] = row[offset:][::-1]
					segment -= len(row) - offset
					break
				else:
					row[offset:offset + segment] = row[offset:offset + segment][::-1]
					offset = offset + segment
					segment = 0
		ans = 0
		for row in plan:
			row = [(v, i) for (i, v) in enumerate(row)]
			row.sort()
			row = [i for (v, i) in row]
			seat = [0 for _ in range(m)]
			for i in row:
				seat[i] = 1
				ans += sum(seat[:i])
		print(ans)
main()


a = int(input())
for i in range(a):
	ok = dict()
	(p1, p2) = map(int, input().split())
	p3 = list(map(int, input().split()))
	op = p3[:]
	for j in range(p1 * p2):
		ok[p3[j]] = []
	for j in range(p1 * p2):
		ok[p3[j]].append(j)
	p3 = sorted(p3)
	miss = []
	for j in range(p1 * p2 - 1, -1, -1):
		miss.append(p3[p1 * p2 - 1 - j])
	lol = []
	for t in miss:
		ok[t] = sorted(ok[t])[::-1]
	for j in range(p1 * p2):
		lol.append(ok[miss[j]][-1])
		ok[miss[j]].pop()
	z = []
	for j in range(p1 * p2):
		z.append(0)
	stack = set()
	rez = 0
	for j in range(p1 * p2):
		if j % p2 == 0:
			stack = set()
		for k in stack:
			if k < lol[j] and op[k] != op[lol[j]]:
				rez += 1
		stack.add(lol[j])
	print(rez)


import sys
input = sys.stdin.readline
from bisect import bisect_left as lower_bound

def getSum(BITree, index):
	s = 0
	while index > 0:
		s += BITree[index]
		index -= index & -index
	return s

def updateBIT(BITree, n, index, val):
	while index <= n:
		BITree[index] += val
		index += index & -index

def convert(arr, n):
	temp = [0] * n
	for i in range(n):
		temp[i] = arr[i]
	temp.sort()
	for i in range(n):
		arr[i] = lower_bound(temp, arr[i]) + 1

def findElements(arr, n):
	convert(arr, n)
	BIT = [0] * (n + 1)
	smaller_right = [0] * n
	greater_left = [0] * n
	for i in range(n - 1, -1, -1):
		smaller_right[i] = getSum(BIT, arr[i] - 1)
		updateBIT(BIT, n, arr[i], 1)
	for i in range(1, n + 1):
		BIT[i] = 0
	for i in range(n):
		greater_left[i] = i - getSum(BIT, arr[i])
		updateBIT(BIT, n, arr[i], 1)
	return greater_left

def solve(n, m, a):
	b = sorted(a)
	dec = {}
	for i in range(m * n):
		if a[i] in dec:
			dec[a[i]].append(i)
		else:
			dec[a[i]] = [i]
	for i in dec:
		dec[i] = dec[i][::-1]
	ind = [0] * (m * n)
	for i in range(n * m):
		ind[i] = dec[b[i]].pop()
	mat = []
	for i in range(n):
		mat.append(list((0 for _ in range(m))))
	poi = 0
	for i in range(n):
		for j in range(m):
			mat[i][j] = ind[poi]
			poi += 1
	for i in range(n):
		t = [mat[i][0]]
		l = 0
		for j in range(1, m):
			if a[mat[i][j]] == a[mat[i][j - 1]]:
				t.append(mat[i][j])
			else:
				for ll in range(l, j):
					mat[i][ll] = t.pop()
				t = [mat[i][j]]
				l = j
		for ll in range(l, m):
			mat[i][ll] = t.pop()
	for i in range(n):
		for j in range(m):
			mat[i][j] = -1 * mat[i][j]
	ans = 0
	for i in range(n):
		arr = findElements(mat[i], m)
		ans += sum(arr)
	return ans
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	print(solve(n, m, a))


import os, sys
from io import BytesIO, IOBase
from collections import defaultdict

class SortedList:

	def __init__(self, iterable=None, _load=200):
		if iterable is None:
			iterable = []
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		dct = defaultdict(list)
		for (ind, i) in enumerate(a):
			dct[i].append(ind)
		pos = [0] * (n * m)
		(r, c) = (0, 0)
		for i in sorted(dct.keys()):
			x = dct[i]
			(r1, c1, j, tt) = (r, c + len(x), 0, c)
			while c1 >= m:
				for xx in range(m - 1, tt - 1, -1):
					pos[x[j]] = r1 * m + xx
					j += 1
				r1 += 1
				c1 -= m
				tt = 0
			for xx in range(c1 - 1, tt - 1, -1):
				pos[x[j]] = r1 * m + xx
				j += 1
			(r, c) = (r1, c1)
		x = [SortedList() for _ in range(n)]
		ans = 0
		for (ind, i) in enumerate(a):
			(r, c) = divmod(pos[ind], m)
			ans += x[r].bisect_left(c)
			x[r].add(c)
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def mergeSort(arr, n):
	temp_arr = [0] * n
	return _mergeSort(arr, temp_arr, 0, n - 1)

def _mergeSort(arr, temp_arr, left, right):
	inv_count = 0
	if left < right:
		mid = (left + right) // 2
		inv_count += _mergeSort(arr, temp_arr, left, mid)
		inv_count += _mergeSort(arr, temp_arr, mid + 1, right)
		inv_count += merge(arr, temp_arr, left, mid, right)
	return inv_count

def merge(arr, temp_arr, left, mid, right):
	i = left
	j = mid + 1
	k = left
	inv_count = 0
	while i <= mid and j <= right:
		if arr[i] < arr[j]:
			temp_arr[k] = arr[i]
			k += 1
			i += 1
		else:
			temp_arr[k] = arr[j]
			inv_count += mid - i + 1
			k += 1
			j += 1
	while i <= mid:
		temp_arr[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp_arr[k] = arr[j]
		k += 1
		j += 1
	for loop_var in range(left, right + 1):
		arr[loop_var] = temp_arr[loop_var]
	return inv_count
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	l = [[l[i], i] for i in range(n * m)]
	l.sort()
	ans = 0
	i = 0
	while i < n * m:
		c = []
		d = 0
		while d < m:
			c.append(l[i][-1::-1])
			i += 1
			d += 1
		c = [i[1] for i in sorted(c)]
		ans += m * (m - 1) // 2 - mergeSort(c, m)
	print(ans)


import sys
input = sys.stdin.readline

class fenwicktree:

	def __init__(self, Size):
		self.Tree = [0] * Size

	def add(self, Index, Value):
		Index += 1
		while Index <= len(self.Tree):
			self.Tree[Index - 1] += Value
			Index += Index & -Index

	def get(self, R):
		Value = 0
		while R != 0:
			Value += self.Tree[R - 1]
			R -= R & -R
		return Value

def main():
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	D = dict()
	Key = []
	for a in A:
		if a in D:
			D[a] += 1
		else:
			D[a] = 1
			Key.append(a)
	Key.sort()
	K = len(Key)
	Comp = dict()
	Ninzu = []
	for i in range(K):
		key = Key[i]
		Comp[key] = i
		Ninzu.append(D[key])
	Seg1L = [0] * K
	Seg1R = [0] * K
	Seg2L = [0] * K
	Seg2R = [0] * K
	Extra = [0] * K
	L = 0
	for i in range(K):
		R = L + Ninzu[i]
		Seg1L[i] = L
		LM = L // M
		RM = R // M
		if LM == RM:
			Seg1R[i] = R
		else:
			Seg1R[i] = (LM + 1) * M
			Extra[i] = (RM - LM - 1) * M
			Seg2L[i] = RM * M
			Seg2R[i] = R
		L = R
	Ans = 0
	Seat = [fenwicktree(M) for _ in range(N)]
	for i in range(N * M):
		a = Comp[A[i]]
		if Seg1R[a] - Seg1L[a]:
			Seg1R[a] -= 1
			(h, w) = divmod(Seg1R[a], M)
			Ans += Seat[h].get(w)
			Seat[h].add(w, 1)
		elif Extra[a]:
			Extra[a] -= 1
		else:
			Seg2R[a] -= 1
			(h, w) = divmod(Seg2R[a], M)
			Ans += Seat[h].get(w)
			Seat[h].add(w, 1)
	print(Ans)
T = int(input())
for _ in range(T):
	main()


def mergeSort(myList, count):
	if len(myList) > 1:
		mid = len(myList) // 2
		left = myList[:mid]
		right = myList[mid:]
		mergeSort(left, count)
		mergeSort(right, count)
		i = 0
		j = 0
		k = 0
		while i < len(left) and j < len(right):
			if left[i] < right[j]:
				count[0] += len(right) - j
				myList[k] = left[i]
				i += 1
			else:
				myList[k] = right[j]
				j += 1
			k += 1
		while i < len(left):
			myList[k] = left[i]
			i += 1
			k += 1
		while j < len(right):
			myList[k] = right[j]
			j += 1
			k += 1
count = [0]
for __ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	lis = []
	for (i, j) in enumerate(a):
		temp = i
		lis.append([temp, j])
	lis = sorted(lis, key=lambda x: (x[1], x[0]))
	tot = 0
	for i in range(n):
		arr = []
		for j in range(i * m, (i + 1) * m):
			arr.append(lis[j])
		arr = sorted(arr, key=lambda x: x[0])
		newarr = []
		for jk in arr:
			newarr.append(jk[1])
		count = [0]
		mergeSort(newarr, count)
		tot += count[0]
	print(tot)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]
INF = 10 ** 10

class BIT:

	def __init__(self, n):
		self.size = n
		self.data = [0] * (n + 1)

	def add(self, i, x):
		while i <= self.size:
			self.data[i] += x
			i += i & -i

	def get_sum(self, i):
		s = 0
		while i > 0:
			s += self.data[i]
			i -= i & -i
		return s

	def get_rsum(self, l, r):
		return self.get_sum(r) - self.get_sum(l - 1)

def solve(N, M, A):
	L = []
	for i in range(N * M):
		L.append((A[i], i))
	L.sort(key=lambda x: (x[0], -x[1]))
	Person = collections.defaultdict(list)
	A1 = sorted(A)
	SeatAssign = collections.defaultdict(list)
	for i in range(N * M):
		Person[A[i]].append(i)
		SeatAssign[A1[i]].append(i)
	for l in SeatAssign.values():
		l.sort(key=lambda i: (i // M, -(i % M)), reverse=True)
	Seat = [-1] * (N * M)
	k = 0
	for k in range(N * M):
		(a, i) = L[k]
		Seat[i] = k
	for a in Person:
		for i in Person[a]:
			s = SeatAssign[a].pop()
			Seat[i] = s
	bit = [BIT(N * M + 1) for _ in range(N)]
	score = 0
	for i in range(N * M):
		s = Seat[i] + 1
		score += bit[Seat[i] // M].get_sum(s)
		bit[Seat[i] // M].add(s, 1)
	return score
T0 = int(input())
for _ in range(T0):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	print(solve(N, M, A))


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect, insort_left
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(iinp()):
	(n, m) = mp()
	arr = lmp()
	seats = dd(list)
	sarr = sorted(arr)
	for i in range(n * m):
		ni = i // m
		mi = i % m
		seats[sarr[i]].append((ni, mi))
	seated = l2d(n, 0)
	for (k, l) in seats.items():
		l.sort(key=lambda x: (-x[0], x[1]))
	ans = 0
	for i in range(n * m):
		(ni, mi) = seats[arr[i]].pop()
		ind = bl(seated[ni], arr[i])
		ans += ind
		insort_left(seated[ni], arr[i])
	print(ans)


from collections import defaultdict
import math
NO = 'NO'
YES = 'YES'
MOD = 1000000007
ALPH = 'abcdefghijklmnopqrstuvwxyz'

def input_int():
	return int(input())

def input_list():
	return input().split(' ')

def input_list_int():
	return list(map(int, input_list()))

def list_int_to_str(a, sep=' '):
	return sep.join((str(x) for x in a))
global_ans = []

def pr(a):
	global_ans.append(a)

def z_func(s):
	n = len(s)
	z = [0] * n
	l = r = 0
	for i in range(1, n):
		if r >= i:
			z[i] = min(z[i - l], r - i + 1)
		while z[i] + i < n and s[z[i]] == s[z[i] + i]:
			z[i] += 1
		if i + z[i] - 1 > r:
			l = i
			r = i + z[i] - 1
	return z

def is_prime(n):
	d = 2
	while n % d != 0:
		d += 1
	return d == n

def solve():
	(n, m) = input_list_int()
	a = input_list_int()
	cnt = []
	for i in range(n):
		cnt.append([0] * m)
	tmp = defaultdict(dict)
	a_s = sorted(a)
	rd = defaultdict(dict)
	for i in range(m * n):
		r = math.ceil((i + 1) / m)
		if not r in tmp[a_s[i]]:
			tmp[a_s[i]][r] = i % m
		rd[a_s[i]][r] = i % m
	cnt = []
	for i in range(n):
		cnt.append([0] * m)
	ans = 0
	for i in range(n * m):
		r = rd[a[i]]
		t = [math.inf, 1]
		for (k, v) in r.items():
			if tmp[a[i]][k] > v:
				continue
			t = [0, k]
			break
		ans += sum(cnt[t[1] - 1][0:r[t[1]]])
		cnt[t[1] - 1][r[t[1]]] = 1
		rd[a[i]][t[1]] -= 1
	pr(ans)
query_count = 1
query_count = input_int()
while query_count:
	query_count -= 1
	solve()
for global_ans_line in global_ans:
	print(global_ans_line)


TESTS = int(input())
for t in range(TESTS):
	(n, m) = map(int, input().split())
	people = list(map(int, input().split()))
	seats = people.copy()
	seats.sort()
	lookup = {}
	for (i, s) in enumerate(seats):
		if s not in lookup.keys():
			lookup[s] = [i]
		else:
			lookup[s].append(i)
	inconvenience = 0
	grid = [[0] * m for i in range(n)]
	for key in lookup.keys():
		lookup[key].sort(key=lambda x: -100000 * (x // m) + x % m)
	for p in people:
		index = lookup[p].pop(-1)
		nn = index // m
		mm = index % m
		grid[nn][mm] = 1
		inconvenience += grid[nn][:mm].count(1)
	print(inconvenience)


def main():
	test = int(input())
	from collections import defaultdict
	for _ in range(test):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		b = sorted(a)
		idx = defaultdict(list)
		seq = defaultdict(list)
		step = defaultdict(int)
		for i in range(n * m):
			(x, y) = (i // m, i % m)
			idx[b[i]].append([x, y])
		for i in idx:
			idx[i].sort()
			if idx[i][0][0] < idx[i][-1][0]:
				row = idx[i][0][0]
				t = []
				j = 0
				while j < len(idx[i]):
					if idx[i][j][0] != row:
						t.sort(key=lambda x: -x[1])
						seq[i].extend(t)
						t = [idx[i][j]]
						row = idx[i][j][0]
					else:
						t.append(idx[i][j])
					j += 1
				t.sort(key=lambda x: -x[1])
				seq[i].extend(t)
			else:
				idx[i].sort(key=lambda x: -x[1])
				seq[i].extend(idx[i])
			step[i] = 0
		ans = 0
		seat = [[0] * m for _ in range(n)]
		for (i, c) in enumerate(a):
			(x, y) = seq[c][step[c]]
			step[c] += 1
			for j in range(y):
				ans += seat[x][j]
			seat[x][y] = 1
		print(ans)
	return
main()


from collections import deque

def solve1(c, a):
	sol = 0
	for i in range(1, c):
		sol += sum((a[j] < a[i] for j in range(i)))
	return sol

def solve(n, m, a):
	nums = {}
	for (i, x) in enumerate(a):
		if x not in nums:
			nums[x] = deque()
		nums[x].append(i)
	a.sort()
	i = sol = 0
	while i < n * m:
		arow = a[i:i + m]
		row = [0] * m
		for j in range(m - 1, -1, -1):
			row[j] = nums[arow[j]].popleft()
		sol += solve1(m, row)
		i += m
	return sol
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	print(solve(n, m, a))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	s = sorted(((v, i) for (i, v) in enumerate(a)))
	suma = 0
	for i in range(n):
		start = s[m * i][0]
		end = s[m * (i + 1) - 1][0]
		if start != end:
			primers = 1
			llista = s[m * i:m * (i + 1)]
			llista.sort(key=lambda x: x[1])
			for k in range(m):
				val = llista[k][0]
				suma += sum((llista[j][0] > val for j in range(k + 1, m)))
	print(suma)


class SegmentTree:

	def __init__(self, data, default=0, func=lambda x, y: x + y):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	l = [(a[i], i) for i in range(n * m)]
	l.sort()
	pos = [0] * (n * m)
	extra = 0
	last = -1
	start = -1
	for i in range(n * m):
		if l[i][0] != last:
			last = l[i][0]
			start = i
		fst = max(start, i // m * m)
		extra += i - fst
		pos[l[i][1]] = i
	seg = SegmentTree([0] * (m * n))
	out = 0
	q = []
	for i in range(m * n):
		loc = pos[i]
		rowst = loc // m * m
		out += seg.query(rowst, loc)
		q.append(loc)
		seg[loc] = 1
	print(out - extra)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = [int(x) for x in input().split()]
	ans = [[l[i], i] for i in range(n * m)]
	ans.sort()
	inconv = 0
	cnt = 0
	for i in range(n):
		lst = ans[i * m:i * m + m]
		lst.sort(key=lambda x: x[1])
		for i in range(m):
			for j in range(i):
				if lst[i][0] > lst[j][0]:
					cnt += 1
	print(cnt)


def solve():
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	sit = sorted([[l[i], i] for i in range(n * m)])
	grid = [[0 for i in range(m)] for j in range(n)]
	sit_number = {}
	for x in range(len(sit)):
		sit_number[sit[x][1]] = [x // m, x % m]
	ans = 0
	for i in range(len(l)):
		(x, y) = sit_number[i]
		for c in range(y):
			if grid[x][c] != 0 and grid[x][c] != l[i]:
				ans += 1
		grid[x][y] = l[i]
	print(ans)
T = int(input())
for _ in range(T):
	solve()


import sys
input = lambda : sys.stdin.readline().rstrip()
from bisect import bisect_left
from collections import defaultdict as dd

def solve():
	ans = 0
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	Asort = sorted(A)
	colnum = dd(lambda : dd(lambda : -1))
	colnumcnt = dd(lambda : dd(lambda : 0))
	numcol = dd(set)
	for i in range(N):
		for j in range(M):
			a = Asort[M * i + j]
			colnum[i][a] = j
			numcol[a].add(i)
			colnumcnt[i][a] += 1
	q = [[] for _ in range(N)]
	for a in A:
		temp = sorted(numcol[a])
		for i in temp:
			if colnumcnt[i][a] <= 0:
				continue
			pos = bisect_left(q[i], a)
			ans += pos
			colnum[i][a] -= 1
			colnumcnt[i][a] -= 1
			if colnumcnt[i][a] == 0:
				numcol[a].remove(i)
			q[i].insert(pos, a)
			break
	print(ans)
	return
T = int(input())
for i in range(1, T + 1):
	solve()


from collections import defaultdict as dd
import math
import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))

def mergeSort(arr, n):
	temp_arr = [0] * n
	return _mergeSort(arr, temp_arr, 0, n - 1)

def _mergeSort(arr, temp_arr, left, right):
	inv_count = 0
	if left < right:
		mid = (left + right) // 2
		inv_count += _mergeSort(arr, temp_arr, left, mid)
		inv_count += _mergeSort(arr, temp_arr, mid + 1, right)
		inv_count += merge(arr, temp_arr, left, mid, right)
	return inv_count

def merge(arr, temp_arr, left, mid, right):
	i = left
	j = mid + 1
	k = left
	inv_count = 0
	while i <= mid and j <= right:
		if arr[i] <= arr[j]:
			temp_arr[k] = arr[i]
			k += 1
			i += 1
		else:
			temp_arr[k] = arr[j]
			inv_count += mid - i + 1
			k += 1
			j += 1
	while i <= mid:
		temp_arr[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp_arr[k] = arr[j]
		k += 1
		j += 1
	for loop_var in range(left, right + 1):
		arr[loop_var] = temp_arr[loop_var]
	return inv_count

def solve():
	(n, m) = mi()
	s = lm()
	s = list(enumerate(s))
	s.sort(key=lambda x: x[1])
	current = None
	running = []
	seats = []
	for i in range(n * m):
		if s[i][1] == current:
			running.append(s[i])
			pass
		else:
			row = len(seats) // m
			left = m - len(seats) % m
			running.sort(key=lambda x: x[0])
			first = list(reversed(running[:left]))
			for j in range(len(first)):
				seats.append(first[j][0])
			for k in range((len(running) - left + m - 1) // m):
				cur = list(reversed(running[left + k * m:left + (k + 1) * m]))
				for j in range(len(cur)):
					seats.append(cur[j][0])
			running = [s[i]]
			current = s[i][1]
	left = m - len(seats) % m
	running.sort(key=lambda x: x[0])
	first = list(reversed(running[:left]))
	for j in range(len(first)):
		seats.append(first[j][0])
	for k in range((len(running) - left + m - 1) // m):
		cur = list(reversed(running[left + k * m:left + (k + 1) * m]))
		for j in range(len(cur)):
			seats.append(cur[j][0])
	seats_to_people = [seats[k * m:(k + 1) * m] for k in range(n)]
	tot = 0
	for row in seats_to_people:
		tot += mergeSort(list(reversed(row)), len(row))
	print(tot)
q = nn()
for _ in range(q):
	solve()


import types
_atcoder_code = "\n# Python port of AtCoder Library.\n\n__version__ = '0.0.1'\n"
atcoder = types.ModuleType('atcoder')
exec(_atcoder_code, atcoder.__dict__)
_atcoder_fenwicktree_code = "\nimport typing\n\n\nclass FenwickTree:\n    '''Reference: https://en.wikipedia.org/wiki/Fenwick_tree'''\n\n    def __init__(self, n: int = 0) -> None:\n        self._n = n\n        self.data = [0] * n\n\n    def add(self, p: int, x: typing.Any) -> None:\n        assert 0 <= p < self._n\n\n        p += 1\n        while p <= self._n:\n            self.data[p - 1] += x\n            p += p & -p\n\n    def sum(self, left: int, right: int) -> typing.Any:\n        assert 0 <= left <= right <= self._n\n\n        return self._sum(right) - self._sum(left)\n\n    def _sum(self, r: int) -> typing.Any:\n        s = 0\n        while r > 0:\n            s += self.data[r - 1]\n            r -= r & -r\n\n        return s\n"
atcoder.fenwicktree = types.ModuleType('atcoder.fenwicktree')
exec(_atcoder_fenwicktree_code, atcoder.fenwicktree.__dict__)
import sys
import collections
IS_INTERACTIVE = False
input = input
if not IS_INTERACTIVE:
	(*data,) = sys.stdin.read().split('\n')[::-1]

	def input():
		return data.pop()

def fprint(*args, **kwargs):
	print(*args, **kwargs, flush=True)

def eprint(*args, **kwargs):
	print(*args, **kwargs, file=sys.stderr)

def solve_row(local_users, sights):
	users = local_users
	sights = [sights[u] for u in users]
	compressor = {v: i for (i, v) in enumerate(sorted(set(sights)), start=1)}
	sights = [compressor[v] for v in sights]
	users_idx = sorted(range(len(users)), key=lambda i: users[i])
	fw = atcoder.fenwicktree.FenwickTree(max(sights) + 1)
	ans = 0
	for idx in users_idx:
		u = users[idx]
		sight = sights[idx]
		inc = fw.sum(0, sight)
		ans += inc
		fw.add(sight, 1)
	return ans
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	(*sights,) = map(int, input().split())
	users = sorted(range(n * m), key=lambda i: sights[i])
	ans = 0
	for row in range(n):
		local_users = users[row * m:(row + 1) * m]
		ans += solve_row(local_users, sights)
	print(ans)


import sys
input = sys.stdin.readline

class Bit:

	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)

	def range_sum(self, l, r):
		return self.sum(r - 1) - self.sum(l - 1)

	def sum(self, i):
		i += 1
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def get(self, i):
		return self.sum(i) - self.sum(i - 1)

	def add(self, i, x):
		i += 1
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

def main():
	(n, m) = map(int, input().split())
	alst = list(map(int, input().split()))
	alst = [(a, i) for (i, a) in enumerate(alst)]
	alst.sort(key=lambda x: (x[0], x[1]))
	row = [[] for _ in range(n)]
	for (j, (a, i)) in enumerate(alst):
		row[j // m].append((i, a))
	ans = 0
	for alst in row:
		alst.sort()
		se = set()
		alst = [a for (i, a) in alst]
		se = set(alst)
		lst = sorted(se)
		dic = {a: i for (i, a) in enumerate(lst)}
		alst = [dic[a] for a in alst]
		l = len(lst)
		bit = Bit(l)
		for a in alst:
			ans += bit.sum(a - 1)
			bit.add(a, 1)
	print(ans)
for _ in range(int(input())):
	main()


from collections import Counter, deque, defaultdict
from heapq import *
import math

def inp():
	return int(input())

def mapInput():
	return map(int, input().split())

def arrInput():
	return list(map(int, input().split()))

def task():
	(n, m) = mapInput()
	t = arrInput()
	a = []
	for i in range(n * m):
		a.append((t[i], i))
	a.sort(key=lambda x: (x[0], x[1]))
	res = 0
	total = n * m
	for i in range(n):
		x = i * m
		a[x:x + m] = sorted(a[x:x + m], key=lambda x: (x[0], -x[1]))
		for j in range(1, m):
			curr = a[x + j][1]
			for y in range(j):
				index = x + y
				if a[index][1] < curr:
					res += 1
	return res
for _ in range(inp()):
	print(task())


class Dsu:

	def __init__(self, n):
		self.parent = list(range(n))
		self.rank = [1] * n

	def find(self, x):
		while x != self.parent[x]:
			self.parent[x] = self.parent[self.parent[x]]
			x = self.parent[x]
		return x

	def union(self, x, y):
		(px, py) = (self.find(x), self.find(y))
		if px == py:
			return False
		if self.rank[py] > self.rank[px]:
			(px, py) = (py, px)
		self.parent[py] = px
		self.rank[px] += self.rank[py]
		return True

	def get_size(self, x):
		return self.rank[self.find(x)]

class SegTree:

	def __init__(self, arr):
		self.tree = array.array('i', [0] * (2 * len(arr)))
		self.n = len(arr)
		for i in range(self.n):
			self.tree[i + self.n] = arr[i]
		for i in range(self.n - 1, 0, -1):
			self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]

	def update(self, i, val):
		i += self.n
		self.tree[i + self.n] = val
		while i > 1:
			self.tree[i // 2] = self.tree[i] + self.tree[i + 1]
			i //= 2

	def query(self, l, r):
		(res, l, r) = (0, l + self.n, r + self.n)
		while l < r:
			if l & 1:
				res += self.tree[l]
				l += 1
			if r & 1:
				r -= 1
				res += self.tree[r]
			l //= 2
			r //= 2
		return res

	def top(self):
		return self.tree[1]

class Comba:

	def __init__(self, mod):
		self.fact = array.array('i', [0] * MX)
		self.fact[0] = 1
		self.fact_inv = array.array('i', [0] * MX)
		self.mod = mod
		for i in range(1, MX):
			self.fact[i] = self.fact[i - 1] * i % self.mod
		self.fact_inv[MX - 1] = pow(self.fact[MX - 1], self.mod - 2, self.mod)
		for i in range(MX - 2, -1, -1):
			self.fact_inv[i] = self.fact_inv[i + 1] * (i + 1) % self.mod

	def ncr(self, n, r):
		if r > n or n < 0 or r < 0:
			return 0
		return self.fact[n] * self.fact_inv[r] % self.mod * self.fact_inv[n - r] % self.mod

	def npr(self, n, r):
		if r > n or n < 0 or r < 0:
			return 0
		return self.fact[n] * self.fact_inv[n - r] % self.mod

def lcm(x, y):
	return x * y // gcd(x, y)

def rw_file():
	sys.stdin = open('', 'r')
	sys.stdout = open('', 'w')

def re(data=str):
	return data(sys.stdin.readline().rstrip())

def mp(data=str):
	return map(data, sys.stdin.readline().split())
import sys, array
from bisect import bisect_left, bisect_right, insort_left
from math import ceil, floor, log, sqrt, gcd
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
(mod, mod9, nl, MX) = (1000000007, 998244353, '\n', 200003)

def solve(tc):
	(n, m) = mp(int)
	a = list(mp(int))
	sa = sorted(((a[i], i) for i in range(n * m)))
	grid = [[0] * m for i in range(n)]
	stk = defaultdict(list)
	ans = 0
	for i in range(n * m - 1, -1, -1):
		stk[sa[i][0]].append(sa[i][1])
	for cur in range(len(sa)):
		(i, j) = (cur // m, cur % m)
		grid[i][j] = sa[cur][0]
	for i in range(n):
		for j in range(m - 1, -1, -1):
			grid[i][j] = stk[grid[i][j]].pop()
	for i in range(n):
		for j in range(m):
			for k in range(j - 1, -1, -1):
				if grid[i][k] < grid[i][j]:
					ans += 1
	print(ans)
	return None

def main():
	cases = 1
	cases = re(int)
	for case in range(cases):
		solve(case + 1)
main()


import sys
input = sys.stdin.readline
from collections import Counter, defaultdict
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	AA = list(map(int, input().split()))
	B = sorted(AA)
	A = []
	for i in range(N):
		A.append(B[i * M:(i + 1) * M])
	visited = set()
	lib = defaultdict(list)
	for i in range(N - 1, -1, -1):
		for j in range(M):
			lib[A[i][j]].append((i, j))
	dat = [[0] * (M + 1) for _ in range(N)]

	def getv(idx, n):
		ans = 0
		while idx > 0:
			ans += dat[n][idx]
			idx -= idx & -idx
		return ans

	def setv(idx, n, val):
		while idx < M + 1:
			dat[n][idx] += val
			idx += idx & -idx

	def place(a):
		(i, j) = lib[a].pop()
		cnt = getv(j + 1, i)
		setv(j + 1, i, 1)
		return cnt
	cnt = 0
	for a in AA:
		cnt += place(a)
	print(cnt)


import sys, bisect
for _ in range(int(sys.stdin.readline())):
	(n, m) = [int(_) for _ in sys.stdin.readline().split()]
	s = [int(_) for _ in sys.stdin.readline().split()]
	s = sorted([*zip(s, list(range(1, n * m + 1)))])
	r = 0
	for i in range(n):
		x = sorted(s[i * m:(i + 1) * m], key=lambda x: (x[0], -x[1]))
		sl = []
		for (_, j) in x:
			idx = bisect.bisect_left(sl, j)
			r += idx
			sl.insert(idx, j)
	sys.stdout.write('%d\n' % r)


import sys
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x + '\n')
debug = lambda x: sys.stderr.write(x + '\n')
writef = lambda x: print('{:.12f}'.format(x))

class BIT:

	def __init__(self, n, values=None):
		self.bit = [0] * (n + 1)
		self.n = n
		self.total = 0
		if values is not None:
			for (i, v) in enumerate(values):
				self.add(i, v)
				self.total += v

	def check(self):
		l = []
		prv = 0
		for i in range(1, self.n + 1):
			val = self.query(i)
			l.append(val - prv)
			prv = val
		print(' '.join(map(str, l)))

	def query(self, i):
		res = 0
		while i > 0:
			res += self.bit[i]
			i -= i & -i
		return res

	def get(self, i):
		return self.query(i + 1) - self.query(i)

	def add(self, i, x):
		i += 1
		if i == 0:
			raise RuntimeError
		self.total += x
		while i <= self.n:
			self.bit[i] += x
			i += i & -i

	def index(self, v):
		if v <= 0:
			return 0
		if self.total < v:
			return self.n
		x = 0
		r = 1
		while r < self.n:
			r = r << 1
		ll = r
		while ll > 0:
			if x + ll < self.n and self.bit[x + ll] < v:
				v -= self.bit[x + ll]
				x += ll
			ll = ll >> 1
		return x
from bisect import bisect_left

def press(l):
	xs = sorted(set(l))
	inds = [None] * len(l)
	for (i, item) in enumerate(l):
		inds[i] = bisect_left(xs, item)
	return (xs, inds)

def sub(l):
	assert len(l) == m
	(_, l) = press(l)
	bit = BIT(m)
	ans = 0
	for v in l:
		ans += bit.query(v)
		bit.add(v, 1)
	return ans
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	index = {}
	for (i, v) in enumerate(a):
		index.setdefault(v, [])
		index[v].append(i)
	ks = sorted(set(a))
	res = []
	ind = 0
	ans = 0
	for k in ks:
		l = index[k]
		l = sorted(l, reverse=1)
		while len(res) + len(l) >= m:
			v = m - len(res)
			res.extend(l[len(l) - v:])
			ans += sub(res)
			l = l[:len(l) - v]
			res = []
		if l:
			res.extend(l)
	print(ans)


class fenwick_tree:
	__slots__ = ['n', 'data']

	def __init__(self, n):
		self.n = n
		self.data = [0] * self.n

	def add(self, p, x):
		p += 1
		while p <= self.n:
			self.data[p - 1] += x
			p += p & -p

	def sum(self, l, r):
		return self._sum(r) - self._sum(l)

	def _sum(self, r):
		s = 0
		while r > 0:
			s += self.data[r - 1]
			r -= r & -r
		return s
import sys
input = lambda : sys.stdin.readline().rstrip()

def solve():
	(N, M) = map(int, input().split())
	As = list(map(int, input().split()))
	a2A = sorted(set(As))
	A2a = {A: a for (a, A) in enumerate(a2A)}
	As = [A2a[A] for A in As]
	A_indices = [[] for _ in range(N * M)]
	for (i, A) in enumerate(sorted(As)):
		n = i // M
		m = i % M
		A_indices[A].append((n, m))
	for indices in A_indices:
		indices.sort(key=lambda t: (t[0], -t[1]), reverse=True)
	fwts = [fenwick_tree(M) for _ in range(N)]
	answer = 0
	for A in As:
		(n, m) = A_indices[A].pop()
		answer += fwts[n].sum(0, m)
		fwts[n].add(m, 1)
	print(answer)
T = int(input())
for _ in range(T):
	solve()


import array
import bisect
import collections
import decimal
import fractions
import heapq
import math
import os
import sys
from collections import Counter
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def ints_get():
	return map(int, input().strip().split())

def list_get():
	return list(map(int, sys.stdin.readline().strip().split()))

def chars_get():
	return list(map(str, sys.stdin.readline().strip().split()))

def output(to_be_printed, end='\n'):
	sys.stdout.write(str(to_be_printed) + end)

def main():
	for _ in range(int(input())):
		(n, m) = ints_get()
		a = list_get()
		dic = collections.defaultdict()
		s = set()
		for i in range(n * m):
			s.add(a[i])
			if a[i] in dic:
				dic[a[i]].append(i + 1)
			else:
				dic.update({a[i]: [i + 1]})
		for i in dic:
			dic[i].sort()
		v = [[]]
		s = sorted(s)
		for i in s:
			p = dic[i]
			q = 0
			val = m - len(v[len(v) - 1])
			w = []
			while val > 0 and q < len(p):
				w.append(p[q])
				val -= 1
				q += 1
			w.reverse()
			v[len(v) - 1].extend(w.copy())
			w = []
			while q < len(p):
				w.append(p[q])
				q += 1
				if len(w) == m:
					w.reverse()
					v.append(w.copy())
					w = []
			if len(w) > 0:
				w.reverse()
				v.append(w.copy())
		count = 0
		for i in v:
			for j in range(len(i)):
				for k in range(j + 1, len(i)):
					if i[k] > i[j]:
						count += 1
		print(count)
	return
main()


from bisect import bisect_left, bisect_right, insort
import os, sys
input = lambda : sys.stdin.buffer.readline().rstrip(b'\r\n')

def dbp(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)
a_str = lambda : input().decode('ascii')
get_int_list = lambda : [int(x) for x in input().split()]
join_str = lambda l, ch=' ': ch.join((str(x) for x in l))

def do_thing():
	(n, m) = get_int_list()
	alist = get_int_list()
	slist = sorted(alist)
	seats = [0] * (n * m)
	total = 0
	for (aidx, a) in enumerate(alist):
		lbound = bisect_left(slist, a)
		ubound = bisect_right(slist, a) - 1
		(row, col) = divmod(lbound, m)
		placed = False
		while row * m <= ubound and row < n:
			col = min(m - 1, ubound - row * m)
			while row * m + col > lbound and col > 0 and seats[row * m + col]:
				col -= 1
			if not seats[row * m + col]:
				seats[row * m + col] = 1
				total += sum(seats[row * m:row * m + col])
				placed = True
				break
			if placed:
				break
			row += 1
		if not placed:
			raise Exception('ruh roh')
	return total
maxcc = 1
maxcc = int(input())
for cc in range(maxcc):
	print(do_thing())


import sys
input = sys.stdin.readline
from operator import itemgetter

def tentou(A):
	LEN = len(A)
	MAX = max(A)
	MIN = min(A)
	BIT = [0] * (MAX - MIN + 2)

	def update(v, w):
		while v <= MAX - MIN + 1:
			BIT[v] += w
			v += v & -v

	def getvalue(v):
		ANS = 0
		while v != 0:
			ANS += BIT[v]
			v -= v & -v
		return ANS
	ANS = 0
	for i in range(LEN):
		bit_ai = A[i] - MIN + 1
		ANS += i
		ANS -= getvalue(bit_ai)
		update(bit_ai, 1)
	return ANS
t = int(input())
for tests in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	compression_dict = {a: ind for (ind, a) in enumerate(sorted(set(A)))}
	A = [compression_dict[a] for a in A]
	X = [[A[i], n * m - i] for i in range(n * m)]
	X.sort(key=itemgetter(1))
	X.sort(key=itemgetter(0))
	MAX = max(A)
	Z = [[] for i in range(MAX + 1)]
	for (a, ind) in X:
		Z[a].append(ind)
	zind = 0
	B = []
	ANS = 0
	while zind < len(Z):
		if len(B) + len(Z[zind]) <= m:
			B += Z[zind]
			zind += 1
		else:
			r = m - len(B)
			B += Z[zind][-r:]
			Z[zind] = Z[zind][:-r]
		if len(B) == m:
			ANS += tentou(B)
			B = []
	print(ANS)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	arr = list(map(int, input().split()))
	a = []
	k = 0
	for i in arr:
		a.append((i, k))
		k += 1
	a.sort()
	ans = 0
	for i in range(0, n * m, m):
		y = a[i:i + m]
		y.sort(key=lambda x: x[1])
		for j in range(1, m):
			jj = 0
			while jj < j:
				if y[jj][0] < y[j][0]:
					ans += 1
				jj += 1
	print(ans)


def argsort(seq):
	return sorted(range(len(seq)), key=seq.__getitem__)
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	x_all = list(map(int, input().split()))
	sorted_x = argsort(x_all)
	cnt = 0
	for k in range(n):
		x = sorted(sorted_x[k * m:(k + 1) * m])
		d = dict()
		for i in range(m):
			for k in d:
				if x_all[x[i]] > k:
					cnt += d[k]
			if x_all[x[i]] in d:
				d[x_all[x[i]]] += 1
			else:
				d[x_all[x[i]]] = 1
	print(cnt)


from collections import Counter
test = int(input())
for t in range(test):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	freq = Counter(arr)
	A = [(arr[i], i) for i in range(n * m)]
	A.sort()
	newIndex = {A[i]: i for i in range(n * m)}
	inconvinence = 0
	seatOccupied = [[0] * m for i in range(n)]
	for i in range(n * m):
		desiredIndex = newIndex[arr[i], i]
		desiredRow = desiredIndex // m
		desiredCol = desiredIndex % m
		fullSeats = 0
		seatOccupied[desiredRow][desiredCol] = arr[i]
		for j in range(desiredCol):
			if seatOccupied[desiredRow][j]:
				fullSeats += 1
		inconvinence += fullSeats
	for row in range(n):
		(cnt, col) = (0, 1)
		while col < m:
			if seatOccupied[row][col] != seatOccupied[row][col - 1]:
				inconvinence -= cnt * (cnt + 1) // 2
				cnt = 0
			else:
				cnt += 1
			col += 1
		inconvinence -= cnt * (cnt + 1) // 2
	print(inconvinence)