It is the easy version of the problem. The only difference is that in this version $n = 1$.

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$ ($n = 1$, $1 \le 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
4
1 3
1 2 3
1 5
2 1 5 3 3
1 2
2 1
1 6
2 3 2 1 1 1
Output
3
6
0
1


-----Note-----

In the first test case, there is a single way to arrange people, because all sight levels are distinct. The first person will sit on the first seat, the second person will sit on the second place, the third person will sit on the third place. So inconvenience of the first person will be $0$, inconvenience of the second person will be $1$ and inconvenience of the third person will be $2$. The total inconvenience is $0 + 1 + 2 = 3$.

In the second test case, people should sit as follows: $s_1 = 2$, $s_2 = 1$, $s_3 = 5$, $s_4 = 4$, $s_5 = 3$. The total inconvenience will be $6$.

Source: codeforces | Difficulty: EASY
Tags: Sorting

Data structures

Greedy algorithms


Solutions:
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()))
	st = []
	st.append(a[0])
	ans = 0
	for i in range(1, m):
		k = 0
		for j in range(len(st)):
			if st[j] < a[i]:
				k += 1
		st.append(a[i])
		ans += k
	print(ans)


def main():
	in_n = int(input())
	for _ in range(in_n):
		(n, m) = input().rstrip().split()
		m = int(m)
		sights = input().rstrip().split()
		sights = [int(s) for s in sights]
		inc = 0
		for i in range(m - 1):
			inc += sum([sights[j] < sights[i + 1] for j in range(i + 1)])
		print(inc)
main()


from collections import defaultdict

def calc_badness(aa, n, m):
	aax = list(enumerate(aa))
	aax.sort(key=lambda x: (x[1], -x[0]))
	badness = 0
	added = set()
	for (i, a) in aax:
		for j in range(0, i):
			if j in added:
				badness += 1
		added.add(i)
	return badness
n_samples = int(input())
for t in range(n_samples):
	(n, m) = map(int, input().split(' '))
	aa = list(map(int, input().split(' ')))
	assert len(aa) == n * m
	print(calc_badness(aa, n, n))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	a = []
	for i in range(m):
		a.append([A[i], i])
	a.sort()
	b = [0] * m
	s = 0
	for i in range(m):
		b[a[i][1]] = 1
		s = s + sum(b[0:a[i][1]])
	A.sort()
	i = 0
	while i < m:
		c = A.count(A[i])
		s = s - (c * (c - 1) >> 1)
		i = i + c
	print(s)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	freq = {}
	for item in a:
		if item in freq:
			freq[item] += 1
		else:
			freq[item] = 1
	temp = 0
	for (key, val) in sorted(freq.items()):
		temp += val
		freq[key] = temp
	l = []
	for i in range(len(a)):
		l.append(freq[a[i]])
		freq[a[i]] -= 1
	vac = [0] * (m + 1)
	ic = 0
	for i in range(m):
		for j in range(l[i]):
			if vac[j] == 1:
				ic += 1
		vac[l[i]] = 1
	print(ic)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	inconv = 0
	copy = []
	for i in range(m):
		copy.append(0)
	for i in range(m):
		plist = l[::-1]
		if l.count(min(l)) > 1:
			pos = m - 1 - plist.index(min(l))
		else:
			pos = l.index(min(l))
		inconv += copy[:pos].count(1)
		copy[pos] = 1
		l[pos] = 99999999999
	print(inconv)


try:
	T = int(input())
	for i in range(T):
		(n, m) = map(int, input().split())
		L = list(map(int, input().split()))
		cnt = 0
		for i in range(1, len(L)):
			for j in range(i - 1, -1, -1):
				if L[j] < L[i]:
					cnt += 1
		print(cnt)
except:
	pass


def solve():
	(n, m) = [int(x) for x in input().split()]
	arr = [int(x) for x in input().split()]
	b = sorted(arr)
	seat_repartition = dict()
	(i, seat_index) = (0, 1)
	while i < n * m:
		j = i + 1
		while j < n * m:
			if b[j] != b[i]:
				break
			j += 1
		seat_repartition[b[i]] = seat_index + j - i - 1
		seat_index = seat_index + j - i
		i = j
	for seat_index in seat_repartition.values():
		assert 1 <= seat_index
		assert n * m >= seat_index
	inconvenience = 0
	person_inconvenience = 0
	(occupied, free) = (1, 0)
	seats = []
	for _ in range(n):
		seats.append([free] * m)
	for person_index in range(n * m):
		sight_level = arr[person_index]
		max_ = seat_repartition[sight_level]
		seat_repartition[sight_level] = max_ - 1
		row = max_ // m
		if max_ % m == 0:
			row -= 1
		seat_index = max_ - m * row
		occupied_slots = len([x for x in seats[row][:seat_index] if x == occupied])
		inconvenience += occupied_slots
		seats[row][seat_index - 1] = occupied
	return inconvenience
for _ in range(int(input())):
	print(solve())


import bisect
import collections
import functools
import heapq
import itertools
import math
import random
import sys
import time
input = sys.stdin.readline

def ri():
	return int(input())

def rf():
	return list(map(float, input().split()))

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

def rs():
	return input().rstrip()

def out_list(x):
	return ' '.join(map(str, x))
MOD = 10 ** 9 + 7
INF = float('inf')

def solve_case():
	(n, m) = rl()
	A = rl()
	s = [(a, i) for (i, a) in enumerate(A)]
	s.sort(key=lambda x: (x[0], -x[1]))
	res = 0
	seats = [INF] * m
	idx = 0
	for (a, i) in s:
		seats[idx] = i
		idx += 1
		res += sum((seats[j] < i for j in range(idx)))
	print(res)
T = int(input())
for test_case in range(1, T + 1):
	solve_case()


import math
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	w = sorted(enumerate(a), key=lambda x: (x[1], -x[0]))
	flag = [0 for i in range(m)]
	total_inconvenience = 0
	d = {}
	for i in range(len(w)):
		d[w[i][0]] = i
	for i in range(n * m):
		for j in range(d[i]):
			total_inconvenience += flag[j]
		flag[d[i]] = 1
	print(total_inconvenience)


def result(row, seat_in_rows, eye_sight):
	seated = [False] * seat_in_rows
	abc = eye_sight.copy()
	abc.sort()
	final_problem = 0
	for i in eye_sight:
		for j in range(-1, -(seat_in_rows + 1), -1):
			if abc[j] == i and seated[j] == False:
				seated[j] = True
				qqq = 0
				for k in range(seat_in_rows + j):
					if seated[k] == True:
						qqq += 1
				final_problem += qqq
				break
	print(final_problem)
for i in range(int(input())):
	abc = list(map(int, input().split()))
	abd = list(map(int, input().split()))
	result(abc[0], abc[1], abd)


from collections import deque, defaultdict, Counter
from itertools import product, groupby, permutations, combinations, accumulate, zip_longest, combinations_with_replacement
from math import gcd, floor, inf, log2, sqrt, log10, factorial
from bisect import bisect_right, bisect_left, insort_left
from statistics import mode
from string import ascii_lowercase, ascii_uppercase
from heapq import heapify, heappop, heappush, heappushpop, heapreplace, nlargest, nsmallest, merge
from copy import deepcopy
cases = int(input())
for _ in range(cases):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	new_arr = []
	ans = 0
	for num in arr:
		ans += bisect_left(new_arr, num)
		insort_left(new_arr, num)
	print(ans)


_ = 1
_ = int(input())
while _ > 0:
	_ -= 1
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	c = 0
	for x in range(1, m):
		for y in range(x):
			if l[y] < l[x]:
				c += 1
	print(c)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	w = list(map(int, input().split()))
	c = 0
	for i in range(m):
		for j in range(i):
			if w[i] > w[j]:
				c += 1
	print(c)


from sys import stdin, stdout
input = stdin.readline

def output(answer):
	stdout.write('{}\n'.format(answer))
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	dp = sorted(arr)
	pos = [None for i in range(m)]
	for index in range(m):
		for j in range(m - 1, -1, -1):
			if arr[index] == dp[j]:
				dp[j] = None
				pos[index] = j
				break
	dp = [False for i in range(m)]
	count = 0
	for p in pos:
		for i in range(p):
			if dp[i] == True:
				count += 1
		dp[p] = True
	output(count)


try:
	import sys
	import math
	import collections
	M = 10 ** 9 + 7

	def solve():
		(n, m) = map(int, input().split())
		arr = list(map(int, input().split()))
		temp = arr.copy()
		temp.sort()
		total = [0] * m
		d = collections.defaultdict(lambda : 0)
		for i in arr:
			d[i] += 1
		count = 0
		for i in range(m):
			for j in range(m):
				if arr[i] == temp[j]:
					index = j + (d[arr[i]] - 1)
					total[index] = 1
					d[arr[i]] -= 1
					break
				elif total[j] == 1:
					count += 1
		return count
		n = int(input())
		A = input()
		B = input()
		A = A.replace('\r', '')
		B = B.replace('\r', '')
		new_A = ''
		i = 0
		cou = 0
		while i < n:
			if A[i] == '0' and B[i] == '1' or (A[i] == '1' and B[i] == '0'):
				cou += 2
				i += 1
			elif A[i] == '1' and B[i] == '1' and (i < n - 1):
				if A[i + 1] == '0' and B[i + 1] == '0':
					cou += 2
					i += 2
				else:
					cou += 0
					i += 1
			elif A[i] == '1' and B[i] == '1':
				i += 1
			elif A[i] == '0' and B[i] == '0' and (i < n - 1):
				if A[i + 1] == '1' and B[i + 1] == '1':
					cou += 2
					i += 2
				else:
					cou += 1
					i += 1
			elif A[i] == '0' and B[i] == '0':
				cou += 1
				i += 1
			else:
				i += 1
		return cou
		for i in range(0, n):
			if A[i] == '1' and B[i] == '1':
				new_A += '1'
			elif A[i] == '0' and B[i] == '1' or (A[i] == '1' and B[i] == '0'):
				cou += 2
			else:
				new_A += '0'
		if len(new_A) == 0:
			return cou
		new_B = '' + new_A[0]
		for i in range(1, len(new_A)):
			if new_A[i] == '1' and new_A[i - 1] == '1':
				pass
			else:
				new_B += new_A[i]
		count_one = new_B.count('1')
		count_zero = new_B.count('0')
		if count_one > count_zero:
			cou += 2 * count_zero
		else:
			cou += 2 * count_one + (count_zero - count_one)
		return cou
		count_0 = new_string.count('0')
		if count_0 == 0:
			return 0
		elif count_0 == 1:
			return 1
		elif count_0 > 1:
			return 2
		else:
			return 2
		if n % 2:
			return k // (n // 2 + 1)
		else:
			return k // (n // 2 + 1)
		temp = modularExponentiation(2, n) - 1
		return modularExponentiation(temp, k)
	test = int(input())
	count1 = 1
	while count1 <= test:
		ans = solve()
		sys.stdout.write(str(ans) + '\n')
		count1 += 1
except EOFError:
	print('')


t = int(input())
for test in range(t):
	(n, m) = map(int, input().split())
	array = list(map(int, input().split()))
	array2 = sorted(array)
	init = 0
	status = [False for i in range(m)]
	for item in array:
		s = array2.index(item)
		while s < m and array2[s] == item:
			s += 1
		s -= 1
		array2[s] = -1
		for i in range(s):
			if status[i] == True:
				init += 1
		status[s] = True
	print(init)


import sys
import math as mt
import collections as cc
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
xor = [0]
for tc in range(int(input())):
	(n, m) = I()
	ar = I()
	f = cc.defaultdict(int)
	temp = sorted(ar)
	ans = 0
	for i in range(1, m):
		if temp[i] != temp[i - 1]:
			f[temp[i - 1]] = i - 1
	f[temp[-1]] = m - 1
	visi = [0] * m
	for i in range(m):
		cur = f[ar[i]]
		visi[cur] = 1
		f[ar[i]] -= 1
		ans += sum(visi[:cur])
	print(ans)


import bisect
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().rstrip().split()))
	a = list(map(int, input().rstrip().split()))
	ans = []
	final = 0
	for i in range(m):
		final += bisect.bisect_left(ans, a[i])
		bisect.insort(ans, a[i])
	print(final)


t = int(input())
for tt in range(t):
	(n, m) = [int(i) for i in input().split()]
	arr = [[i, int(a)] for (i, a) in enumerate(input().split())]
	sarr = sorted(arr, key=lambda x: (x[1], -x[0]))
	for i in range(len(sarr)):
		sarr[i].append(i)
	mus = 0
	for i in range(1, len(arr)):
		xam = [0]
		xam.extend([x[2] for x in arr[:i] if x[2] < arr[i][2]])
		mus += len(xam) - 1
	print(mus)


t = int(input())
while t:
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	count = 0
	for i in range(m):
		for j in range(i):
			if arr[j] < arr[i]:
				count += 1
	print(count)
	t -= 1


for __ in range(int(input())):
	(n, m) = map(int, input().split())
	s = list(map(int, input().split()))
	o = [s[0]]
	ans = 0
	for i in range(1, m):
		for j in range(len(o)):
			if s[i] > o[j]:
				ans += 1
		o.append(s[i])
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = sorted(a)
	d = [0 for i in range(m)]
	res = 0
	for i in range(m):
		for j in range(m - 1, -1, -1):
			if b[j] == a[i] and d[j] == 0:
				d[j] = 1
				for h in range(j):
					if d[h] == 1:
						res += 1
				break
	print(res)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = 0
	for i in range(m):
		for j in range(i):
			if a[i] > a[j]:
				c += 1
	print(c)


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 i in range(n):
		temp.append([-arr[i], i])
	already = []
	temp = sorted(temp)
	ans = 0
	for i in range(n):
		ans += temp[i][1] - bisect.bisect(already, temp[i][1])
		bisect.insort(already, temp[i][1])
	print(ans)
T = int(input())
t = 1
while t <= T:
	main(t)
	t += 1


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, m) = list(map(int, stdin.readline().split()))
	a = list(map(int, stdin.readline().split()))
	b = sorted(enumerate(a), key=lambda x: (x[1], -x[0]))
	c = [0] * m
	for i in range(m):
		c[b[i][0]] = i
	res = 0
	cur = [0] * m
	for i in range(m):
		s = c[i]
		for j in range(s):
			res += cur[j]
		cur[s] = 1
	print(res)


t = int(input())
for tt in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	for i in range(n * m):
		a[i] = (a[i], i)
	a.sort(key=lambda element: element[1], reverse=True)
	a.sort(key=lambda element: element[0])
	s = [0 for i in range(n * m)]
	for i in range(n * m):
		s[a[i][1]] = i
	po = [[0 for i in range(m)] for j in range(n)]
	sum = 0
	for i in range(n * m):
		for k in range(s[i]):
			sum += po[0][k]
		po[0][s[i]] = 1
	print(sum)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	s = 0
	d = [int(i) for i in input().split()]
	for i in range(m):
		for j in range(i + 1, m):
			if d[j] > d[i]:
				s += 1
	print(s)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lst = [[0, 0] for _ in range(m)]
	for (index, key) in enumerate(map(int, input().split())):
		lst[index][0] = key
		lst[index][1] = -index
	lst = sorted(lst)
	places = [0 for _ in range(m)]
	ans = 0
	for i in range(m):
		cnt = 0
		for j in range(m):
			if lst[j][1] == -i:
				places[j] = 1
				ans += cnt
				break
			cnt += places[j]
	print(ans)


import sys
for _ in range(int(sys.stdin.readline())):
	(n, m) = [int(x) for x in sys.stdin.readline().split()]
	a = [int(x) for x in sys.stdin.readline().split()]
	c = 0
	for i in range(m):
		for j in range(i - 1, -1, -1):
			if a[i] > a[j]:
				c += 1
	sys.stdout.write(str(c) + '\n')


from collections import Counter, defaultdict
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	dat = [0] * (M + 1)

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

	def setv(idx, val):
		while idx < M + 1:
			dat[idx] += val
			idx += idx & -idx
	B = dict(Counter(A))
	T = sorted(list(B.keys()))
	path = defaultdict(list)
	t = 1
	for i in T:
		for k in range(B[i]):
			path[i].append(t)
			t += 1
	cnt = 0
	for i in A:
		idx = path[i].pop()
		cnt += getv(idx)
		setv(idx, 1)
	print(cnt)


t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	audi = list(zip(range(m), map(int, input().split())))
	audi.sort(key=lambda tup: (tup[1], -tup[0]))
	inconv = 0
	for (loc, person) in enumerate(audi):
		for other in audi[loc + 1:]:
			if other[0] > person[0]:
				inconv += 1
	print(inconv)


t = int(input())

def bs(arr, start, end):
	ans = -1
	while start <= end:
		mid = (start + end) // 2
		if arr[mid] <= k:
			ans = mid
			start = mid + 1
		else:
			end = mid - 1
	return ans + 1

class segment_tree_mergesort:

	def __init__(self, arr):
		self.arr = arr
		self.l = len(arr)
		import math
		h = math.floor(math.log2(self.l) + 1)
		self.st = [[] for x in range(2 ** (h + 1) + 1)]
		self.si = 1
		self.ss = 0
		self.se = self.l - 1
		self.__buildmintree(self.si, self.ss, self.se)

	def __buildmintree(self, si, ss, se):
		if ss == se:
			self.st[si] = [self.arr[ss]]
			return True
		mid = (ss + se) // 2
		self.__buildmintree(2 * si, ss, mid)
		self.__buildmintree(2 * si + 1, mid + 1, se)
		i = 0
		j = 0
		while i < len(self.st[2 * si]) and j < len(self.st[2 * si + 1]):
			if self.st[2 * si][i] <= self.st[2 * si + 1][j]:
				self.st[si].append(self.st[2 * si][i])
				i += 1
			else:
				self.st[si].append(self.st[2 * si + 1][j])
				j += 1
		while i < len(self.st[2 * si]):
			self.st[si].append(self.st[2 * si][i])
			i += 1
		while j < len(self.st[2 * si + 1]):
			self.st[si].append(self.st[2 * si + 1][j])
			j += 1

	def query(self, si, ss, se, qs, qe):
		if se < qs or qe < ss:
			return 0
		if qs <= ss and se <= qe:
			return bs(self.st[si], 0, len(self.st[si]) - 1)
		mid = (ss + se) // 2
		l = self.query(2 * si, ss, mid, qs, qe)
		r = self.query(2 * si + 1, mid + 1, se, qs, qe)
		return l + r
while t:
	t -= 1
	(n, m) = [int(x) for x in input().split()]
	arr = [int(x) for x in input().split()]
	s = segment_tree_mergesort(arr)
	ans = 0
	for i in range(m):
		k = arr[i] - 1
		ans += s.query(1, 0, m - 1, 0, i)
	print(ans)


def solve(n, m, a):
	count = 0
	for i in range(1, m):
		for j in range(i - 1, -1, -1):
			if a[i] > a[j]:
				count += 1
	return count
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	print(solve(n, m, arr))


import sys, math

def solve():
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	r = []
	r.append(l[0])
	ans = 0
	for i in range(1, m):
		count_ans = 0
		for j in range(0, len(r)):
			if r[j] < l[i]:
				count_ans += 1
		r.append(l[i])
		ans += count_ans
	print(ans)
t = int(input())
while t != 0:
	solve()
	t -= 1


def seatingArrangement(m, array):
	if m == 1:
		return 0
	pos = []
	ar = sorted(array)
	ar.sort()
	for x in range(m):
		p = len(ar) - 1 - ar[::-1].index(array[x])
		ar[p] = None
		pos.append(p)
	ans = 0
	for x in range(m):
		for y in range(0, x):
			if pos[x] > pos[y]:
				ans += 1
	return ans
t = int(input())
final = []
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	final.append(seatingArrangement(m, l))
for _ in range(t):
	print(final[_])


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

def int_list_input():
	a = list(map(int, input().split()))
	return a

def solve():
	(n, m) = int_list_input()
	arr = int_list_input()
	d = {}
	ans = 0
	for i in arr:
		for j in d:
			if j < i:
				ans += d[j]
		d[i] = d.get(i, 0) + 1
	print(ans)
for _ in range(int(input())):
	solve()


rows = int(input())
for r in range(rows):
	nm = input().split(' ')
	n = int(nm[0])
	m = int(nm[1])
	_l = input().split(' ')
	prio_list = [int(i) for i in _l]
	prio_list_zip = list(zip(prio_list, [-i for i in range(m)]))
	prio_list_zip.sort()
	total = 0
	for i in range(m):
		my_neg_order = prio_list_zip[i][1]
		total += sum([j[1] > my_neg_order for j in prio_list_zip[:i]])
	print(total)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	seat = {}
	ans = 0
	temp = []
	for i in range(m):
		temp.append([a[i], i])
	temp.sort(key=lambda x: (x[0], -x[1]))
	for i in range(m):
		for j in range(m):
			if temp[j][1] == i:
				break
			elif temp[j][1] < i:
				ans += 1
	print(ans)


import bisect
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	h = []
	s = 0
	for i in l:
		j = bisect.bisect_left(h, i)
		s += j
		h.insert(j, i)
	print(s)


from itertools import permutations, combinations
import math

def solution():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	st = []
	st.append(a[0])
	count = 0
	for i in range(m):
		if i == 0:
			continue
		k = 0
		for j in range(len(st)):
			if st[j] < a[i]:
				k += 1
		st.append(a[i])
		count += k
	print(count)
t = int(input())
for loop in range(t):
	solution()


import bisect
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	asort = a.copy()
	asort.sort()
	ocu = [False] * m
	ans = 0
	for i in range(m):
		t = bisect.bisect_right(asort, a[i]) - 1
		while ocu[t]:
			t -= 1
		for j in range(t):
			if ocu[j]:
				ans += 1
		ocu[t] = True
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	o = sorted(range(m * n), key=lambda i: (a[i], -i))
	c = 0
	s = [False] * (m * n)
	for i in range(m * n):
		j = o.index(i)
		s[j] = True
		c += sum(s[:j])
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	a = sorted(arr)
	d = {}
	for i in range(n * m):
		if a[i] in d:
			d[a[i]].append(i)
		else:
			d[a[i]] = [i]
	res = [0] * (n * m)
	incv = 0
	for i in arr:
		k = d[i].pop()
		res[k] = 1
		incv += sum(res[:k])
	print(incv)


import sys
from functools import lru_cache
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()
		s = [(v, -i) for (i, v) in enumerate(seats)]
		s.sort()
		s = [-i for (v, i) in s]
		seat = [0 for _ in seats]
		ans = 0
		for i in s:
			seat[i] = 1
			ans += sum(seat[:i])
		print(ans)
main()


def count_smaller_before(lst, idx):
	c = 0
	for i in range(idx):
		if lst[i] < lst[idx]:
			c += 1
	return c
test_amount = int(input())
for _ in range(test_amount):
	sizes = input()
	n = int(sizes.split(' ')[0])
	m = int(sizes.split(' ')[1])
	input_str = input()
	input_list = [int(i) for i in input_str.split(' ')]
	min = 0
	for i in range(len(input_list)):
		min += count_smaller_before(input_list, i)
	print(min)


for _ in range(int(input().strip())):
	(n, m) = map(int, input().strip().split())
	arr = list(map(int, input().strip().split()))
	incon = 0
	for i in range(len(arr)):
		for j in range(i, len(arr)):
			if arr[j] > arr[i]:
				incon += 1
	print(incon)


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)


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
for _ in range(rn()):
	(n, m) = rns()
	a = rl()
	d = defaultdict(list)
	people = sorted(a)
	for i in range(m):
		d[people[i]].append(i)
	taken = [0 for i in range(m)]
	ans = 0
	for num in a:
		i = d[num].pop()
		ans += taken[:i].count(1)
		taken[i] = 1
	print(ans)


test = int(input())
for i in range(test):
	(n, m) = map(int, input().split())
	lol = list(map(int, input().split()))
	c = 0
	for x in range(len(lol)):
		for y in range(x):
			if lol[x] > lol[y]:
				c += 1
	print(c)


import sys
input = sys.stdin.readline
tests = int(input())
for test in range(tests):
	(n, m) = map(int, input().split())
	persons = list(map(int, input().split()))
	inconvenience = 0
	for (idx, person) in enumerate(persons):
		for seated in persons[0:idx]:
			if seated < person:
				inconvenience += 1
	print(inconvenience)


for i in range(int(input())):
	ppl = int(input().split()[1])
	aa = input().split()
	int_aa = [int(a) for a in aa]
	su = 0
	for pp in range(ppl):
		for j in range(pp):
			if int_aa[j] < int_aa[pp]:
				su += 1
	print(su)


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
t = int(input())
for _ in range(t):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	q = list(range(m))
	q.sort(key=lambda x: a[x] - x / 10000)
	slist = []
	inc = 0
	for i in q:
		if slist == []:
			slist.append(i)
		else:
			p = pos(slist, i)
			inc += p
			slist.insert(p, i)
	print(inc)


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
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 = []
	for k in ks:
		l = index[k]
		l.sort()
		res.extend(l[::-1])
	bit = BIT(m)
	ans = 0
	for v in res:
		ans += bit.query(v)
		bit.add(v, 1)
	print(ans)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	personid_and_a = [[0] * 2 for j in range(m)]
	for personid in range(m):
		personid_and_a[personid][0] = personid
		personid_and_a[personid][1] = a[personid]
	personid_and_a.reverse()
	personid_and_a = sorted(personid_and_a, key=lambda x: x[1])
	ans = 0
	tmpvalue = 0
	for j in range(m):
		tmpvalue = personid_and_a[j][0]
		for k in range(0, j):
			if personid_and_a[k][0] < tmpvalue:
				ans += 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())
	ta = TreeArray(m + 2)
	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 = {}
	for i in range(m):
		mp.setdefault(cs2[i][1], i + 1)
	for mc in cs:
		c = mp[mc]
		ans += ta.sum(c - 1)
		ta.update(c, 1)
	print(ans)


test = int(input())
for _ in range(test):
	(n, m) = map(int, input().split())
	sights = list(map(int, input().split()))
	arr = []
	for i in range(m):
		arr.append([sights[i], -1 * i])
	arr = sorted(arr)
	result = 0
	for i in range(m):
		sights[-1 * arr[i][1]] = i
	for i in range(m):
		for j in range(i):
			if sights[i] > sights[j]:
				result += 1
	print(result)


for _ in range(int(input())):
	(m, n) = map(int, input().split())
	l = [int(i) for i in input().split()]
	ct = 0
	for i in range(len(l)):
		for j in range(i):
			if l[j] < l[i]:
				ct += 1
	print(ct)


for iii in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	a = [i for i in enumerate(a)]
	a.sort(key=lambda x: (x[1], -x[0]), reverse=False)
	l = list(enumerate([i[0] for i in a]))
	l.sort(key=lambda x: x[1])
	lst = [0] * m
	l = [i[0] for i in l]
	ans = 0
	for event in l:
		tmp = 0
		for j in range(event):
			tmp += lst[j]
		lst[event] = 1
		ans += tmp
	print(ans)


from __future__ import division, print_function
import os
import 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
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')
import collections, string, bisect, re, random, queue, itertools, statistics, math
from collections import *
from bisect import *
from string import *
from itertools import *
from statistics import *
from math import *
from re import *
from queue import *

class Stack:

	def __init__(self):
		self.items = []

	def push(self, item):
		self.items.append(item)

	def pop(self):
		return self.items.pop()

	def empty(self):
		return self.items == []

	def size(self):
		return len(self.items)

	def at(self, idx):
		try:
			return self.items[idx]
		except:
			return -1

class priority_queue(object):

	def __init__(self):
		self.queue = []

	def __str__(self):
		return ' '.join([str(i) for i in self.queue])

	def empty(self):
		return len(self.queue) == 0

	def push(self, data):
		self.queue.append(data)

	def pop(self):
		try:
			max = 0
			for i in range(len(self.queue)):
				if self.queue[i] > self.queue[max]:
					max = i
			item = self.queue[max]
			del self.queue[max]
			return item
		except IndexError:
			print()
			exit()
mod = int(1000000000.0 + 7)
imax = float('inf')
imin = float('-inf')
true = True
false = False
N = int(100000.0 + 10)
none = None
inp = lambda : input()
I = lambda : int(inp())
M = lambda : map(int, inp().split())
MS = lambda : map(str, inp().split())
S = lambda : list(MS())
L = lambda : list(M())

def IO():
	try:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('uttar.txt', 'w')
	except:
		pass
IO()

def kabraji_ka_totka():
	(n, m) = L()
	arr = L()
	res = 0
	new = [[]]
	for i in range(m):
		res += len([x for x in arr[:i] if arr[i] > x])
	print(res)
for i in range(I()):
	kabraji_ka_totka()


t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	arr = [(a[i], i + 1) for i in range(m)]
	arr.sort(key=lambda x: [x[0], -x[1]])
	dp = [0] * (m + 1)
	count = 0
	for i in range(m):
		seat = arr.index((a[i], i + 1))
		seat += 1
		dp[seat] = 1
		count += sum(dp[:seat])
	print(count)


import sys
from collections import Counter

def func(n, m, a):
	visited = [a[0]]
	c1 = 0
	for i in range(1, m):
		c2 = 0
		for j in range(len(visited)):
			if a[i] > visited[j]:
				c2 += 1
		c1 += c2
		visited.append(a[i])
	return c1
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	print(func(n, m, a))


def merge(arr):
	if len(arr) <= 1:
		return (0, arr)
	n = len(arr)
	half = n // 2
	(arr1, arr2) = (arr[:half], arr[half:])
	(v1, arr1) = merge(arr1)
	(v2, arr2) = merge(arr2)
	rt = v1 + v2
	(i, j, len1, len2) = (0, 0, len(arr1), len(arr2))
	arr3 = []
	while i < len1 or j < len2:
		if i == len1:
			rt += len1 - i
			arr3.append(arr2[j])
			j += 1
			continue
		if j == len2 or arr1[i] >= arr2[j]:
			arr3.append(arr1[i])
			i += 1
			continue
		rt += len1 - i
		arr3.append(arr2[j])
		j += 1
	return (rt, arr3)
for t in range(int(input())):
	(n, m) = input().rstrip().split()
	(n, m) = (int(n), int(m))
	arr = input().rstrip().split()
	arr = [int(x) for x in arr]
	sort_arr = sorted(arr)
	idx = {}
	for (i, v) in enumerate(sort_arr):
		idx[v] = i
	place = []
	for (i, v) in enumerate(arr):
		place.append(idx[v])
		idx[v] -= 1
	copy_place = place[:]
	ans = merge(copy_place)[0]
	print(ans)


for i in range(int(input())):
	(n, m) = input().split()
	a = [int(x) for x in input().split()]
	ll = list()
	ll.append(int(a[0]))
	ans = 0
	for i in range(int(m)):
		if i == 0:
			continue
		k = 0
		for j in range(len(ll)):
			if ll[j] < a[i]:
				k += 1
		ll.append(a[i])
		ans += k
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	s = 0
	a = []
	for i in range(m):
		a.append(l[i])
		a.sort()
		s = s + a.index(l[i])
	print(s)


from math import *
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	n = m
	a = list(map(int, input().split()))
	b = sorted(a)
	d = {}
	for i in range(n - 1):
		if b[i] != b[i + 1]:
			d[b[i]] = i
	d[b[-1]] = n - 1
	filled = [0 for i in range(n)]
	ans = 0
	for i in range(n):
		c = a[i]
		m = d[a[i]]
		for j in range(m):
			if filled[j] == 1:
				ans += 1
		filled[d[a[i]]] = 1
		d[a[i]] -= 1
	print(ans)


import time
import os, sys
from datetime import datetime
from math import floor, sqrt, gcd, factorial, ceil, log2
from collections import Counter, defaultdict
import bisect
from itertools import chain
from collections import deque
from sys import maxsize as INT_MAX
from itertools import permutations
from collections import deque
(ONLINE_JUDGE, INF, mod) = (False, float('inf'), int(1000000000.0) + 7)
if os.path.exists('D:\\vimstuff'):
	ONLINE_JUDGE = True
	sys.stdin = open('inp.txt', 'r')
	sys.stdout = open('out.txt', 'w')

def readint():
	return int(sys.stdin.readline())

def readstr():
	return sys.stdin.readline()

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

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

def mulfloat():
	return map(float, sys.stdin.readline().strip().split())

def flush():
	return sys.stdout.flush()

def power_two(x):
	return 1 << x

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

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
			return n - leftGreater

def lower_bound(arr, n, val):
	(l, r) = (-1, n)
	while r > l + 1:
		m = int(l + r >> 1)
		if arr[m] < val:
			l = m
		else:
			r = m
	return r

def upper_bound(arr, n, val):
	(l, r) = (-1, n)
	while r > l + 1:
		m = int(l + r >> 1)
		if arr[m] <= val:
			l = m
		else:
			r = m
	return l

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

def printmat(l, seperate=True):
	for i in range(0, len(l)):
		if seperate:
			print(*l[i], sep=' ')
		else:
			print(*l[i], sep='')

def is_perfect_square(num):
	temp = num ** 0.5
	return temp // 1 == temp

def find(res):
	n1 = res
	while par[n1] != n1:
		par[n1] = par[par[n1]]
		n1 = par[n1]
	return n1

def union(u, v):
	(p1, p2) = (find(u), find(v))
	if p1 == p2:
		return 0
	if rank[p1] > rank[p2]:
		(p1, p2) = (p2, p1)
	par[p1] = p2
	rank[p2] += rank[p1]
	return 1

def compress(n, a):
	s = sorted(a)
	d = {}
	cnt = 0
	for i in range(0, n):
		try:
			if d[s[i]]:
				continue
		except:
			d[s[i]] = cnt
			cnt += 1
	for i in range(0, n):
		a[i] = d[a[i]]
	return a

def john_3_16():
	(n, m) = readmul()
	a = readlst()
	a = compress(m, a)
	ans = [INF] * m
	mx = -INF
	lastind = {}
	d = Counter(a)
	(cnt, prev) = (0, 0)
	for i in range(0, m):
		try:
			if d[i]:
				prev = prev + d[i]
				lastind[i] = prev
				mx = max(mx, i)
		except:
			continue
	for i in range(0, m):
		curr = lastind[a[i]]
		for j in range(0, curr):
			if ans[j] != INF:
				cnt += 1
		ans[curr - 1] = a[i]
		lastind[a[i]] -= 1
	print(cnt)
	return

def main():
	tc = readint()
	start = time.time()
	while tc:
		john_3_16()
		tc -= 1
	if ONLINE_JUDGE:
		print(f'{(time.time() - start) * 1000}ms')
		pass
main()


from sys import stdin
inp = stdin.readline
t = int(inp())
for _ in range(t):
	(m, n) = map(int, inp().split())
	arr = [int(x) for x in inp().split()]
	count = 0
	s = []
	for i in range(n):
		s.append(arr[i])
		s.sort()
		count += s.index(arr[i])
	print(count)


import sys
input = sys.stdin.readline

def solve(n, a):
	arr = [[a[i], i] for i in range(n)]
	arr.sort(key=lambda x: (x[0], -x[1]))
	places = [i[1] for i in arr]
	ans = 0
	for i in range(1, n):
		for j in range(i):
			if places[j] < places[i]:
				ans += 1
	return ans
t = int(input())
for _ in range(t):
	(n, b) = map(int, input().split())
	a = list(map(int, input().split()))
	print(solve(b, a))


n = int(input())
i = 0
while i < n:
	m2 = input().split()
	m = int(m2[1])
	st = input().split()
	k = 0
	inc = 0
	p = []
	while k < m:
		s = int(st[k])
		p.append(s)
		p.sort()
		inc = p.index(s) + inc
		k = k + 1
	print(inc)
	i = i + 1


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = 0
	for k in range(len(a)):
		count = 0
		for j in range(k):
			if a[k] > a[j]:
				count += 1
		ans += count
	print(ans)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	prev = []
	ans = 0
	for i in l:
		curr = 0
		for j in prev:
			if j < i:
				curr += 1
		ans += curr
		prev.append(i)
	print(ans)


def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		if m == 1:
			print(0)
			continue
		a = list(a[::-1])
		ind = list(sorted(a))
		c = '1'
		ans = 0
		for i in ind:
			a[a.index(i)] = c
			c = str(int(c) + 1)
		a = [int(i) for i in a[::-1]]
		for i in range(1, m):
			ans += sum([1 if j < a[i] else 0 for j in a[:i]])
		print(ans)
main()


for fghj in range(int(input())):
	(m, n) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	v = [[a[i], -i] for i in range(n)]
	v.sort(key=lambda x: (x[0], x[1]))
	for i in range(n):
		v[i][1] *= -1
	final = [-1 for i in range(n)]
	ans = 0
	for i in range(n):
		t = v[i][1]
		for i in range(t):
			if final[i] != -1:
				ans += 1
		final[t] = 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(m - 1):
		for j in range(i + 1, m):
			if a[j] > a[i]:
				ans += 1
	print(ans)


import math
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = [(j, i) for (i, j) in enumerate(map(int, input().split()))]
	a.sort(key=lambda x: (x[0], -x[1]))
	ans = 0
	occ = [0 for _ in range(len(a))]
	pos = [0 for _ in range(len(a))]
	j = 0
	for (x, i) in a:
		pos[i] = j
		j += 1
	for i in pos:
		inc = 0
		for j in range(i):
			inc += occ[j]
		occ[i] = 1
		ans += inc
	print(ans)


n = int(input())
o = []
for i in range(n):
	(a, b) = map(int, input().split())
	l = list(map(int, input().split()))
	t = 0
	for p in range(b):
		for q in range(p):
			if l[p] > l[q]:
				t += 1
	print(t)


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
	for i in range(n):
		x = i * n
		c = 0
		for j in range(1, m):
			curr = a[x + j][1]
			for y in range(j):
				index = x + y
				if a[index][1] < curr:
					c += 1
		res += c
	return res
for _ in range(inp()):
	print(task())


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 * m):
		b[-a[i][1]] = i
	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()


import sys
input = sys.stdin.readline
for i in range(int(input())):
	k = 0
	(n, m) = map(int, input().split())
	l = [*map(int, input().split())]
	s = [0] * m
	gg = sorted(l, reverse=1)
	for i in range(m):
		s[m - gg.index(l[i]) - 1] = 1
		k += s[:m - gg.index(l[i]) - 1].count(1)
		gg[gg.index(l[i])] = -1
	print(k)


import sys
read = lambda : sys.stdin.readline()
from bisect import bisect_left
for _ in range(int(read())):
	(n, m) = map(int, read().split())
	a = list(map(int, read().split()))
	khaali = []
	ans = 0
	for num in a:
		idx = bisect_left(khaali, num)
		khaali.insert(idx, num)
		ans += idx
	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()
	tmp = {}
	a_s = sorted(a)
	for i in range(m):
		tmp[a_s[i]] = i
	ans = 0
	cnt = [0] * m
	for i in range(m):
		v = tmp[a[i]]
		for j in range(v):
			if cnt[j]:
				ans += 1
		cnt[v] = 1
		tmp[a[i]] -= 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)


from typing import Collection
from collections import Counter
t = int(input())
for q in range(t):
	(n, m) = [int(x) for x in input().split()]
	arr = [int(x) for x in input().split()]
	c = Counter(arr)
	lis = sorted(arr)
	vec = [0 for i in range(m)]
	count = 0
	for i in range(m):
		ind = lis.index(arr[i])
		count += vec[:ind].count(1)
		vec[ind + c[arr[i]] - 1] = 1
		c[arr[i]] -= 1
	print(count)


def inconv(f, n):
	c = 0
	for i in f:
		if i < n:
			c += f[i]
	return c
for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	f = dict()
	c = 0
	for i in a:
		c += inconv(f, i)
		f[i] = f.get(i, 0) + 1
	print(c)


class bst_node(object):

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

class Solution(object):

	def add_node(self, bst_pointer, new_node, position):
		if bst_pointer == None:
			return (position, new_node)
		if new_node.val < bst_pointer.val:
			bst_pointer.left_count += 1
			(position, bst_pointer.left) = self.add_node(bst_pointer.left, new_node, position)
		else:
			if new_node.val > bst_pointer.val:
				position += 1
			position += bst_pointer.left_count
			(position, bst_pointer.right) = self.add_node(bst_pointer.right, new_node, position)
		return (position, bst_pointer)

	def countSmaller(self, nums):
		res = []
		bst = None
		for n in nums[::-1]:
			(smaller_after, bst) = self.add_node(bst, bst_node(n), 0)
			res.append(smaller_after)
		return res[::-1]
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	arr.reverse()
	print(sum(Solution().countSmaller(arr)))


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	c = 0
	for i in range(m):
		c += len([x for x in a[:i] if a[i] > x])
	print(c)


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
T = int(readline())
for t in range(T):
	(N, M) = map(int, readline().split())
	A = list(map(int, readline().split()))
	ans = 0
	for j in range(M):
		for i in range(j):
			if A[i] < A[j]:
				ans += 1
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
	(n, m) = map(int, input().split())
	a = [*map(int, input().split())]
	ans = 0
	for i in range(m):
		for j in range(i):
			if a[i] > a[j]:
				ans += 1
	print(ans)
	t -= 1


import math
import sys
from math import cos, pi, ceil, pi, tan, floor, gcd, sqrt, log2, factorial, log10
from collections import Counter
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase
from statistics import mean, median, mode
from bisect import *
alpha = ascii_lowercase
beta = ascii_uppercase

def nextPowerOf2(n):
	p = 1
	if n and (not n & n - 1):
		return n
	while p < n:
		p <<= 1
	return p

def get_Divisors(n):
	arr = []
	i = 1
	while i <= sqrt(n):
		if n % i == 0:
			if n / i == i:
				arr.append(i)
			else:
				arr.append(i)
				arr.append(n // i)
		i = i + 1
	return arr

def isprime(n):
	if n == 1:
		return 0
	i = 2
	while i * i <= n:
		if n % i == 0:
			return 0
		i += 1
	return 1

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

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def create_matrix(n, m):
	mat = [[] for i in range(n)]
	for i in range(n):
		for j in range(m):
			mat[i].append(0)
	return mat

def main():
	for ttt in range(int(input())):
		(n, m) = map(int, input().split())
		ar = list(map(int, input().split()))
		s = deepcopy(ar)
		arr = [[ar[i], i] for i in range(m)]
		ss = [[s[i], i] for i in range(m)]
		arr.sort(key=lambda k: (k[0], -k[1]))
		res = [-1] * m
		summ = 0
		for i in range(m):
			ind = 0
			for j in range(m):
				if ss[i][0] == arr[j][0] and ss[i][1] == arr[j][1]:
					ind = j
			res[ind] = 1
			for ii in range(ind):
				if res[ii] == 1:
					summ += 1
		print(summ)
main()


numTests = int(input())
for t in range(numTests):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	total_inconvenience = 0
	for (i, e) in enumerate(a):
		inconvenience = 0
		for j in range(0, i):
			if a[j] < e:
				inconvenience += 1
		total_inconvenience += inconvenience
	print(total_inconvenience)


for t in range(int(input())):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	S = sorted(set(A))
	D = dict()
	for i in range(len(S)):
		D[S[i]] = i
	for i in range(M):
		A[i] = D[A[i]]
	X = [0] * M
	ANS = 0
	for i in range(M):
		X[A[i]] += 1
		for j in range(A[i]):
			ANS += X[j]
	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], 1 / (x[0] + 1)))
	ans = 0
	for i in range(m):
		temp = 0
		for j in range(i):
			if a[j] < a[i]:
				temp += 1
		ans += temp
	print(ans)


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(m)]
	A.sort()
	newIndex = {A[i]: i for i in range(m)}
	inconvinence = 0
	seatOccupied = [0] * m
	for i in range(m):
		desiredIndex = newIndex[arr[i], i]
		fullSeats = 0
		seatOccupied[desiredIndex] = 1
		for j in range(desiredIndex):
			if seatOccupied[j]:
				fullSeats += 1
		inconvinence += fullSeats
	for key in freq:
		if freq[key] > 1:
			inconvinence -= freq[key] * (freq[key] - 1) // 2
	print(inconvinence)


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

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	(_, n) = value()
	a = array()
	ans = 0
	places = [-1] * n
	for i in range(n):
		pos = n - 1
		for j in range(i + 1, n):
			if a[j] > a[i]:
				pos -= 1
				ans += 1
		while places[pos] != -1 and pos >= 0:
			pos -= 1
		places[pos] = i
	print(ans)


def solve(arr):
	targets = [0] * len(arr)
	seats = [0] * len(arr)
	result = sorted([(v, i) for (i, v) in enumerate(arr)], key=lambda t: (t[0], -t[1]))
	idx = 0
	x = 0
	for (place, i) in result:
		targets[i] = idx
		idx += 1
	for (guy, place) in zip(arr, targets):
		x += sum(seats[:place])
		seats[place] = 1
	return x
for _ in '_' * int(input()):
	input()
	print(solve([*map(int, input().split())]))


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	x = list(map(int, input().split()))
	cnt = 0
	for i in range(m):
		for j in range(i):
			if x[i] > x[j]:
				cnt += 1
	print(cnt)


import sys, os, io
from functools import cmp_to_key
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

class SegmentTree:

	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):
		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)

def fun(a, b):
	if a[0] > b[0]:
		return 1
	elif a[0] < b[0]:
		return -1
	elif a[1] > b[1]:
		return -1
	else:
		return 1
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [[a[i], i] for i in range(len(a))]
	b.sort(key=cmp_to_key(fun))
	vis = [0] * m
	st = SegmentTree(vis)
	ans = 0
	for i in b:
		st.__setitem__(i[1], 1)
		ans += st.query(0, i[1])
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	mm = list(map(int, input().split()))
	for i in range(m):
		a.append([mm[i], i])
	a = sorted(a, key=lambda x: (x[0], -x[1]))
	for i in range(m):
		a[i].append(i)
	a = sorted(a, key=lambda x: x[1])
	res = [0 for i in range(m)]
	rr = 0
	for el in a:
		rr += sum(res[0:el[-1]])
		res[el[-1]] = 1
	print(rr)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	d = 0
	for i in range(m):
		for j in range(i):
			if l[j] < l[i]:
				d += 1
	print(d)


import sys
import math
t = int(sys.stdin.readline())
for _ in range(t):
	line = sys.stdin.readline().strip()
	(n, m) = [int(x) for x in line.split()]
	a = [int(x) for x in sys.stdin.readline().strip().split()]
	s = 0
	d = {}
	for e in a:
		v = d.get(e, 0)
		s_part = 0
		for k in d.keys():
			if k < e:
				s_part += d.get(k)
		d[e] = v + 1
		s += s_part
	print(s)


import math
from collections import Counter, deque
from math import *
mod = 998244353

def solve():
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	d = {}
	l1 = l.copy()
	l1.sort()
	for i in range(m - 1, -1, -1):
		if l1[i] in d:
			d[l1[i]].append(i)
		else:
			d[l1[i]] = deque()
			d[l1[i]].append(i)
	visit = [0] * m
	count = 0
	for i in l:
		x = d[i][0]
		for j in range(x):
			if visit[j]:
				count += 1
		visit[d[i].popleft()] = 1
	print(count)
t = int(input())
for _ in range(t):
	solve()


from sys import stdin
from bisect import bisect, insort
for testcase in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	sights = list(map(int, stdin.readline().split()))
	sightIndices = {}
	for index in range(n * m):
		if sights[index] in sightIndices:
			sightIndices[sights[index]].append(index)
		else:
			sightIndices[sights[index]] = [index]
	sightsOrder = sorted(sightIndices)
	seatingOrderByIndices = []
	for sight in sightsOrder:
		seatingOrderByIndices.extend(sightIndices[sight][::-1])
	occupiedSeats = []
	inconvenience = 0
	for seating in seatingOrderByIndices:
		inconvenience += bisect(occupiedSeats, seating)
		insort(occupiedSeats, seating)
	print(inconvenience)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	v = sorted(l)
	ans = [0] * m
	ic = 0
	vis = [0] * m
	for i in range(m):
		x = m - 1
		for j in range(m - 1, -1, -1):
			if v[j] == l[i] and vis[j] == 0:
				vis[j] = 1
				x = j
				break
		ans[x] = 1
		ic += ans[:x].count(1)
	print(ic)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	assert n == 1
	visions = list(map(int, input().split()))
	suma2 = 0
	for i in range(m):
		for j in range(i + 1, m):
			if visions[j] > visions[i]:
				suma2 += 1
	print(suma2)


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)


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 p in people:
		index = lookup[p].pop(-1)
		grid[index] = 1
		inconvenience += grid[:index].count(1)
	print(inconvenience)


def fun(stack, s):
	x1 = s.pop(0)
	x2 = stack.pop()
	ans = 0
	value = []
	while x1 > x2:
		value.append(x2)
		if len(stack) > 0:
			x2 = stack.pop()
		else:
			break
	ans += len(value)
	if x1 > x2:
		stack.append(x1)
		for i in range(len(value)):
			val = value.pop()
			stack.append(val)
	else:
		stack.append(x2)
		stack.append(x1)
		for i in range(len(value)):
			val = value.pop()
			stack.append(val)
	return ans
t = int(input())
while t > 0:
	t -= 1
	mn = input().split()
	n = int(mn[0])
	m = int(mn[1])
	s = input().split()
	s = [int(x) for x in s]
	stack = []
	if m == 1:
		print(0)
	else:
		ans = 0
		temp = s.pop(0)
		stack.append(temp)
		length = len(s)
		for i in range(length):
			ans += fun(stack, s)
		print(ans)


for _ in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	c = 0
	for i in range(m):
		for j in range(i - 1, -1, -1):
			if a[i] > a[j]:
				c += 1
	print(c)


import math
import sys
import collections
import bisect
import time
import random
import itertools
import string
from collections import Counter, defaultdict

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

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

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	(n, m) = get_ints()
	arr = get_list()
	pos_arr = collections.defaultdict(list)
	for (i, j) in enumerate(arr):
		pos_arr[j].append(i)
	eye_sights = list(sorted(pos_arr.keys()))
	for i in eye_sights:
		pos_arr[i].sort(reverse=True)
	seated = [10 ** 10] * m
	pos = 0
	for i in eye_sights:
		for j in pos_arr[i]:
			seated[pos] = j
			pos += 1
	ans = 0
	for i in range(m):
		value = seated[i]
		for j in range(i, -1, -1):
			if seated[j] < value:
				ans += 1
	print(ans)


import sys, os.path, math
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for t in range(int(input())):
	(n, m) = list(map(int, input().split()))
	num = list(map(int, input().split()))
	count = 0
	for i in range(m):
		for j in range(i):
			if num[i] > num[j]:
				count += 1
	print(count)


def main():
	from sys import stdin
	from itertools import islice
	tkns = map(int, stdin.read().split())
	t = next(tkns)
	for _ in range(t):
		(n, m) = (next(tkns), next(tkns))
		p = [0] * m
		a = islice(tkns, m)
		ans = 0
		for (s, _) in sorted(enumerate(a), key=lambda t: (t[1], -t[0])):
			ans += sum(islice(p, s))
			p[s] = 1
		print(ans)
main()


def CountInconv(arr):
	inversions = 0

	def CountInconvSort(arr):

		def CountSplit(lArr, rArr):
			i = 0
			j = 0
			k = 0
			nonlocal inversions
			mArr = []
			while i < len(lArr) and j < len(rArr):
				if lArr[i] >= rArr[j]:
					mArr.append(lArr[i])
					i += 1
				else:
					mArr.append(rArr[j])
					j += 1
					inversions += len(lArr) - i
				k += 1
			if i < len(lArr):
				mArr += lArr[i:]
			if j < len(rArr):
				mArr += rArr[j:]
			return mArr
		if len(arr) <= 1:
			return arr
		leftArr = CountInconvSort(arr[:len(arr) // 2])
		rightArr = CountInconvSort(arr[len(arr) // 2:])
		sortedArr = CountSplit(leftArr, rightArr)
		return sortedArr
	CountInconvSort(arr)
	return inversions
cases = int(input())
for case in range(cases):
	(r, c) = [int(x) for x in input().split()]
	seats = [int(x) for x in input().split()]
	print(CountInconv(seats))


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


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	k = 0
	sits = ['0'] * m
	arr2 = sorted(arr)
	for i in range(m):
		l = 0
		p = 0
		while p < m and arr2[p] != arr[i]:
			l += 1
			p += 1
		while p < m and arr2[p] == arr[i]:
			l += 1
			p += 1
		for j in range(l):
			if sits[j] != '0':
				k += 1
		sits[l - 1] = str(arr[i])
		arr[i] = -1
		arr2[p - 1] = -1
	print(k)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	cop = sorted(a)
	dp = [0 for i in range(m)]
	res = 0
	for cn in range(m):
		start = -1
		for i in range(m - 1, -1, -1):
			if cop[i] == a[cn] and dp[i] == 0:
				dp[i] = 1
				start = i
				break
		for i in range(start - 1, -1, -1):
			if dp[i]:
				res += 1
	print(res)


t = int(input())
while t > 0:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = []
	for i in range(m - 1, -1, -1):
		ans = 0
		for j in range(i):
			if a[j] < a[i]:
				ans = ans + 1
		b.append(ans)
	print(sum(b))
	t = t - 1


T = int(input())
while T > 0:
	T -= 1
	[n, m] = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = a.copy()
	b.sort()
	M = {}
	for i in range(m):
		M[b[i]] = i + 1
	ans = 0
	seats = []
	for i in range(m + 1):
		seats.append(0)
	for i in range(m):
		seat = M[a[i]]
		M[a[i]] -= 1
		ans += sum(seats[:seat])
		seats[seat] = 1
	print(ans)


def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		b = [(x, i) for (i, x) in enumerate(a)]
		b.sort(key=lambda x: n * m * x[0] - x[1])
		s = [0] * m
		for i in range(m):
			s[b[i][1]] = i
		answer = 0
		for i in range(m):
			for j in range(i):
				if s[j] < s[i]:
					answer += 1
		print(answer)
main()


from sys import stdin, stdout
from collections import Counter, deque
from math import *
from functools import reduce
cin = stdin.readline
cout = stdout.write
mod = pow(10, 9) + 7

def inpn():
	return int(cin())

def inpl():
	return list(map(int, cin().split()))

def inpset():
	return set(map(int, cin().split()))

def inps():
	return cin()[:-1]

def inpv():
	return map(int, cin().split())

def inpvf():
	return map(float, cin().split())

def outs(s):
	cout(s)

def outn(n):
	cout(str(n))

def outl(l):
	for i in l:
		cout(str(i) + ' ')

def outb(s):
	cout(str(s))

def endl():
	cout('\n')

def solution():
	(n, m) = inpv()
	l = inpl()
	d = {}
	l1 = l.copy()
	l1.sort()
	for i in range(m - 1, -1, -1):
		if l1[i] in d:
			d[l1[i]].append(i)
		else:
			d[l1[i]] = deque()
			d[l1[i]].append(i)
	already = [0] * m
	ans = 0
	for i in l:
		x = d[i][0]
		for j in range(x):
			if already[j]:
				ans += 1
		already[d[i].popleft()] = 1
	outn(ans)
	endl()
testCase = inpn()
for _ in range(testCase):
	solution()


mydict = {}
t = int(input())
arr = []
for _ in range(t):
	count = 0
	(n, m) = map(int, input().split())
	arr = map(int, input().split(' '))
	dem = 0
	for i in arr:
		dem += 1
		mydict[dem] = i
	for i in range(1, m + 1):
		for j in range(1, i):
			if mydict.get(i) > mydict.get(j):
				count += 1
	print(count)


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(m):
		for j in range(i):
			if a[j] < a[i]:
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	print(len([i for i in range(m) for j in range(i) if a[i] > a[j]]))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ord = list(map(int, input().split()))
	blind = [(x, i) for (x, i) in enumerate(ord)]
	blind.sort(key=lambda x: (x[1], -x[0]), reverse=True)
	occ = [0] * 300
	pos = []
	indx = 300
	uncomf = 0
	for i in blind:
		pos.append((i, indx))
		indx -= 1
	pos.sort(key=lambda x: (x[0][0], -x[1]))
	for i in pos:
		for j in range(i[1]):
			uncomf += occ[j]
		occ[i[1] - 1] = 1
	print(uncomf)


import os
import sys
from io import BytesIO, IOBase

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():
	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))

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		arr = list(map(int, input().split()))
		l = [m - i - 1 for i in range(m)]
		l.sort(key=lambda x: arr[x])
		lst = SortedList()
		ans = 0
		for i in l:
			lst.add(i)
			ans += lst.bisect_left(i)
		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()


import math
from collections import OrderedDict

class node:

	def __init__(self, v):
		self.val = v
		self.next = None
		self.previous = None

class LinkList:

	def __init__(self):
		self.head = None
		self.ans = 0

	def add_node(self, v):
		temp = node(v)
		if self.head == None:
			self.head = temp
		elif temp.val <= self.head.val:
			temp.next = self.head
			self.head.previous = temp
			self.head = temp
		else:
			curr = self.head
			while curr.val < temp.val and curr.next != None:
				curr = curr.next
				self.ans += 1
			if curr.next == None and temp.val > curr.val:
				curr.next = temp
				temp.previous = curr
				self.ans += 1
			else:
				curr.previous.next = temp
				temp.previous = curr.previous
				temp.next = curr
				curr.previous = temp
		return self
t = int(input())
while t > 0:
	inp = input()
	q = list(map(int, inp.split()))
	n = q[0]
	m = q[1]
	inp = input()
	a = list(map(int, inp.split(' ')))
	ll = LinkList()
	for i in range(0, m):
		ll = ll.add_node(a[i])
	print(ll.ans)
	t -= 1


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
from itertools import permutations
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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 = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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:
			self.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 get_int():
	return int(input())

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

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

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

def get_strs():
	return get_str().split(' ')

def flat_list(arr):
	return [item for subarr in arr for item in subarr]

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	return p

def solve_a():
	(n, s) = get_ints()
	return s // ((n + 2) // 2)

def solve_b():
	s = get_str()
	if '0' not in s:
		return 0
	x = [c for c in s.split('1') if c]
	if len(x) == 1:
		return 1
	else:
		return 2

def solve_c():
	n = get_int()
	s1 = get_str()
	s2 = get_str()
	cnt = 0
	i = 0
	while i < n:
		if len({s1[i], s2[i]}) == 2:
			cnt += 2
			i += 1
		elif s1[i] == s2[i] == '0':
			if i < n - 1 and '0' not in {s1[i + 1], s2[i + 1]}:
				cnt += 2
				i += 2
			else:
				cnt += 1
				i += 1
		elif s1[i] == s2[i] == '1':
			if i < n - 1 and '0' in {s1[i + 1], s2[i + 1]}:
				cnt += 2
				i += 2
			else:
				i += 1
	return cnt

def solve_d1():
	(n, m) = get_ints()
	a = get_ints()
	ai = [(x, -i) for (i, x) in enumerate(a)]
	cnt = 0
	for i in range(m):
		for j in range(i + 1, m):
			if ai[i] < ai[j]:
				cnt += 1
	return cnt
t = get_int()
for _ in range(t):
	print(solve_d1())


for __ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	count = 0
	for i in range(m):
		for j in range(i + 1, m):
			if a[j] > a[i]:
				count += 1
	print(count)


import bisect

def solve(s):
	L = sorted(range(len(s)), key=lambda i: (s[i], -i))
	Seen = []
	ans = 0
	for x in L:
		i = bisect.bisect_left(Seen, x)
		ans += i
		Seen.insert(i, x)
	return ans
for _ in range(int(input())):
	__ = input()
	sights = list(map(int, input().split()))
	print(solve(sights))


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	arr = list(map(int, stdin.readline().split()))
	ans = 0
	for i in range(m):
		for j in range(0, i):
			if arr[j] < arr[i]:
				ans += 1
	print(ans)


for _ in range(int(input())):
	(a, b) = map(int, input().split())
	l = list(map(int, input().split()))
	ans = 0
	x = [-1] * b
	for i in range(b):
		for t in range(i + 1, b):
			if l[i] < l[t]:
				ans += 1
	print(ans)


from collections import Counter
for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	s = []
	for i in range(len(a)):
		s.append((a[i], i))
	s.sort(key=lambda x: x[0])
	stack = []
	for (i, j) in s:
		stack.append(j)
	dp = [0] * len(stack)
	ans = 0
	dic = {}
	for i in stack:
		idx = i
		tem = 0
		if a[i] not in dic:
			dp[idx] = 1
			for x in range(i):
				if dp[x] != 0:
					tem += 1
			ans += tem
			dic[a[i]] = 1
		else:
			dp[idx] = 1
			for x in range(i):
				if dp[x] != 0:
					tem += 1
			ans += tem - dic[a[i]]
			dic[a[i]] += 1
	print(ans)


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


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l = [[l1[i], -i] for i in range(m)]
	l.sort()
	s = 0
	for i in range(m):
		for j in range(m):
			if -l[j][1] < i:
				s += 1
			elif -l[j][1] == i:
				break
	print(s)


import sys
LI = lambda : list(map(int, sys.stdin.readline().split()))
MI = lambda : map(int, sys.stdin.readline().split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline())
for _ in range(II()):
	(n, m) = MI()
	a = sorted([(v, -i - 1) for (i, v) in enumerate(LI())])
	o = sorted([(-a[i][1], i) for i in range(m)])
	v = [0] * m
	ans = 0
	for (p, s) in o:
		for i in range(m - 1, s, -1):
			v[i] += 1
		ans += v[s]
	print(ans)


t = int(input())
for i in range(t):
	[n, m] = map(int, input().split())
	a = list(map(int, input().split()))
	st = []
	st.append(a[0])
	ans = 0
	for i in range(m):
		if i == 0:
			continue
		k = 0
		for j in range(len(st)):
			if st[j] < a[i]:
				k += 1
		st.append(a[i])
		ans += k
	print(ans)


from sys import stdin

def solve():
	results = []
	for _ in range(int(stdin.readline().strip())):
		(n, m) = map(int, stdin.readline().strip().split())
		A = list(map(int, stdin.readline().strip().split()))
		seats = []
		ans = 0
		for x in A:
			seats.append(x)
			ans += sum((y < x for y in seats))
		results.append(ans)
	print('\n'.join(map(str, results)))
solve()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = []
	for j in range(len(a)):
		tmp = [a[j], j + 1]
		b.append(tmp)
	b.sort(key=lambda p: (p[0], -p[1]))
	s = 0
	c = [0] * (m + 1)
	for j in range(len(a)):
		for k in range(b[j][1]):
			s = s + c[k]
		c[b[j][1]] = 1
	print(s)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp_vars_int = lambda : map(int, input().split())
inp_list_int = lambda : list(map(int, input().split()))
t = int(input())
for _ in range(t):
	(n, m) = inp_vars_int()
	a = inp_list_int()
	a_ord = [(i, ai) for (i, ai) in enumerate(a)]
	a_ord = sorted(a_ord, key=lambda x: (x[1], -x[0]))
	a_ord = [v[0] for v in a_ord]
	seated = [[0 for _ in range(m)] for _ in range(n)]
	res = 0
	for v in range(n * m):
		p_ord = a_ord[v]
		(r, c) = (p_ord // m, p_ord % m)
		res += sum(seated[r][:c])
		seated[r][c] = 1
	print(res)


def main():
	t = int(input())
	for i in range(t):
		(n, m) = map(int, input().split())
		arr = list(map(int, input().split()))
		start = 0
		total = 0
		while start < m:
			for j in range(start):
				if arr[j] < arr[start]:
					total += 1
			start += 1
		print(total)
main()


n = int(input())
for i in range(n):
	sm = 0
	(a, b) = map(int, input().split())
	arr = [int(x) for x in input().split()]
	while len(arr) != 0:
		k = arr.index(max(arr))
		sm += k
		arr.pop(k)
	print(sm)


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()


def solve(c, a):
	sol = 0
	for i in range(1, c):
		sol += sum((a[j] < a[i] for j in range(i)))
	return sol
t = int(input())
for _ in range(t):
	(_, c) = map(int, input().split())
	a = list(map(int, input().split()))
	print(solve(c, a))


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

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')
getint = lambda : int(sys.stdin.readline().rstrip('\r\n'))
getints = lambda : map(int, sys.stdin.readline().rstrip('\r\n').split())
lgetints = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
getstrs = lambda : map(str, sys.stdin.readline().rstrip('\r\n').split())

def prog_name():
	(n, m) = getints()
	l = lgetints()
	final = [l[0]]
	cnt = 0
	for x in l[1:]:
		c = 0
		temp = 0
		for y in range(len(final)):
			if x <= final[y]:
				final.insert(y, x)
				c += 1
				break
			else:
				temp += 1
			if c == 0 and temp == len(final):
				final.append(x)
		cnt += temp
	print(cnt)

def main():
	T = getint()
	for unique in range(T):
		prog_name()
main()


from collections import deque, Counter
from collections import defaultdict as dfd
from bisect import bisect, bisect_left
from math import sqrt, gcd, ceil, factorial, log2
from heapq import heapify, heappush, heappop
MOD = 10 ** 9 + 7
inf = float('inf')
ans_ = []

def nin():
	return int(input())

def ninf():
	return int(file.readline())

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

def stf():
	return file.readline().strip()

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

def readf():
	return list(map(int, file.readline().strip().split()))

def readfl():
	return list(map(float, input().strip().split()))

def readffl():
	return list(map(float, file.readline().strip().split()))

def solve():

	def update(index, value, array, bi_tree):
		while index <= len(array):
			bi_tree[index] += value
			index += index & -index

	def get_sum(index, bi_tree):
		ans = 0
		while index > 0:
			ans += bi_tree[index]
			index -= index & -index
		return ans
	for _ in range(nin()):
		(n, m) = read()
		BIT = [0] * (m + 5)
		arr = read()
		arr = [[arr[i], i + 1] for i in range(m)]
		arr.sort(key=lambda x: x[0])
		arr = [[arr[i][1], i + 1, arr[i][0]] for i in range(m)]
		arr.sort()
		places = dfd(list)
		for (i, j, k) in arr:
			places[k].append(j)
		ans = 0
		f = [0] * (m + 1)
		for (k, ind, j) in arr:
			indx = places[j].pop()
			tem = get_sum(indx, BIT)
			ans += tem
			update(indx, 1, arr, BIT)
			f[indx] = 1
		ans_.append(ans)
solve()
for i in ans_:
	print(i)


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 i in range(M):
		if A[i] in D:
			D[A[i]].append(i)
		else:
			D[A[i]] = [i]
			Key.append(A[i])
	Key.sort()
	Place = [0] * M
	i = 0
	for key in Key:
		for Num in sorted(D[key], reverse=True):
			Place[Num] = i
			i += 1
	Ans = 0
	BIT = fenwicktree(M)
	for P in Place:
		Ans += BIT.get(P)
		BIT.add(P, 1)
	print(Ans)
T = int(input())
for _ in range(T):
	main()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split(' '))
	s = list(map(int, input().split(' ')))
	compare = lambda x: x[0] - x[1] / m
	order = sorted(zip(s, list(range(1, m + 1))), key=compare)
	count = 0
	for (j, person) in enumerate(order):
		for k in range(j + 1, m):
			person2 = order[k]
			if person2[1] > person[1]:
				count += 1
	print(count)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	c = 0
	for i in range(1, m * n):
		sl = l[0:i]
		ss = l[i]
		sc = 0
		for j in sl:
			if j < ss:
				c += 1
	print(c)


t = int(input())
ans = []
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = [(int(i), j + 1) for (i, j) in zip(input().split(), range(m))]
	arr.sort(key=lambda x: (x[0], -1 * x[1]))
	sm = 0
	for num in range(1, m + 1):
		for i in arr:
			if num == i[1]:
				break
			if num > i[1]:
				sm += 1
	ans.append(sm)
print(*ans, sep='\n')


import sys
input = sys.stdin.readline

def update(inp, add, ar):
	global m
	n = m + 1
	while inp < n:
		ar[inp] += add
		inp += inp & -inp

def summation(inp, ar):
	ans = 0
	while inp:
		ans += ar[inp]
		inp -= inp & -inp
	return ans
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	br = list(map(int, input().split()))
	li = []
	for i in range(m):
		li.append([br[i], i + 1])
	li.sort(key=lambda x: [x[0], -x[1]])
	ans = 0
	ar = [0] * (m + 1)
	for i in range(m):
		seat = li[i][1]
		xx = summation(seat, ar)
		ans += xx
		update(seat, 1, ar)
	print(ans)


import atexit, io, sys, math, heapq

def get_int():
	return int(sys.stdin.readline().strip())

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

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

def get_string():
	return sys.stdin.readline().strip()

def write_int(a):
	sys.stdout.write(str(a) + '\n')

def write_str(a):
	sys.stdout.write(a + '\n')

def write_list(arr):
	sys.stdout.write(' '.join(map(str, arr)) + '\n')

def swap(arr, a, b):
	arr[a] ^= arr[b]
	arr[b] ^= arr[a]
	arr[a] ^= arr[b]

def int_len(a):
	return math.floor(math.log(a, 10)) + 1

def isPowerOfTwo(x):
	return x and (not x & x - 1)

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

def binarySearch(arr, l, r, x):
	if r >= l:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return binarySearch(arr, l, mid - 1, x)
		else:
			return binarySearch(arr, mid + 1, r, x)
	else:
		return -1

def search(arr, x):
	return binarySearch(arr, 0, len(arr) - 1, x)

def toString(A):
	return ''.join(A)

def toArray(str):
	return str.split()

def arrSum(Arr):
	Sum = 0
	for i in range(len(Arr)):
		Sum += Arr[i]
	return Sum

def computeXOR(n):
	if n % 4 == 0:
		return n
	if n % 4 == 1:
		return 1
	if n % 4 == 2:
		return n + 1
	return 0

def Index(alist, value):
	return len(alist) - alist[-1::-1].index(value) - 1

def TrueCount(Arr, limit):
	count = 0
	for i in range(limit):
		if Arr[i] == True:
			count += 1
	return count
N = get_int()
while N > 0:
	Arr1 = get_list()
	count = 0
	A = Arr1[0]
	B = Arr1[1]
	Arr = get_list()
	Arr2 = [0] * B
	for i in range(B):
		Arr2[i] = Arr[i]
	Arr2.sort()
	Bool = [False] * B
	for i in range(B):
		P = Arr[i]
		K = Index(Arr2, P)
		Arr2[K] = 0
		count += TrueCount(Bool, K)
		Bool[K] = True
	print(count)
	N -= 1


import sys
from collections import Counter
from itertools import chain
from itertools import permutations
import math
num_cases = int(sys.stdin.readline().strip())
for case in range(1, num_cases + 1):
	(N, M) = list(map(int, sys.stdin.readline().split()))
	A = list(map(int, sys.stdin.readline().split()))
	real_seat = sorted(A)
	result = 0
	for (index, value) in enumerate(A):
		incon = 0
		for i in range(len(real_seat)):
			if real_seat[i] == value:
				if i != len(real_seat) - 1:
					if real_seat[i + 1] == value:
						continue
					else:
						result += incon
						real_seat[i] = -1
						break
				else:
					result += incon
					real_seat[i] -= 1
					break
			elif real_seat[i] == -1:
				incon += 1
			else:
				continue
	print(result)


import os
import sys
from io import BytesIO, IOBase
from math import inf

def main():
	tc = int(input())
	for _ in range(tc):
		(n, m) = map(int, input().split())
		a = [int(x) for x in input().split()]
		b = sorted(a)
		data = {}
		for i in range(m - 1):
			if b[i] == b[i + 1]:
				continue
			else:
				data[b[i]] = i
		if b[m - 1] not in data.keys():
			data[b[m - 1]] = m - 1
		filled = [0] * m
		counter = 0
		for i in range(m):
			counter += filled[data[a[i]]]
			for j in range(data[a[i]] + 1, m):
				filled[j] += 1
		print(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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def freqUpdater(freq, idx):
	for i in range(idx + 1, len(freq)):
		freq[i] += 1
	return freq
from collections import defaultdict
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	sight = list(map(int, input().split()))
	indexTable = {}
	freqTable = defaultdict(list)
	for (idx, val) in enumerate(sight):
		indexTable[idx] = val
		freqTable[val].append(idx)
	seatTable = {}
	freq = [0 for i in range(m)]
	ans = 0
	seatIdx = 0
	for sight in sorted(freqTable.keys()):
		for (idx, val) in enumerate(freqTable[sight]):
			seatTable[seatIdx + len(freqTable[sight]) - 1 - idx] = val
		seatIdx += len(freqTable[sight])
	for i in range(m):
		ans += freq[seatTable[i]]
		freqUpdater(freq, seatTable[i])
	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())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	ans = 0
	a.reverse()
	for i in range(n * m - 1):
		ans += sum((x < a[i] for x in a[i + 1:]))
	print(ans)


import sys
input = sys.stdin.readline
import bisect
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	w = list(map(int, input().split()))
	d = []
	s = 0
	for i in w:
		j = bisect.bisect_left(d, i)
		d.insert(j, i)
		s += j
	print(s)


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)
tests = inp()
for _ in range(tests):
	(n, m) = input_int_gen()
	a = input_list()
	(sorted, res) = merge_sort(a)
	print(res)


import math
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 OrderedDict
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	ans = 0
	for i in range(m):
		for j in range(i):
			if arr[j] < arr[i]:
				ans += 1
	print(ans)


def solve1():
	(n, s) = map(int, input().split())
	p = (n + 1) // 2
	left = n - p + 1
	print(s // left)

def solve2():
	s = input()
	z = 0
	o = 0
	t = 0
	f = 1
	for i in s:
		if i == '1':
			f = 1
			o = 1
		elif i == '0':
			if f == 1:
				z = z + 1
				f = 0
	print(min(2, z))

def solve3():
	n = int(input())
	s1 = input()
	s2 = input()
	z = 0
	o = 0
	ans = 0
	for i in range(n):
		if s1[i] == '0' and s2[i] == '1' or (s1[i] == '1' and s2[i] == '0'):
			ans = ans + 2 + z
			z = 0
			o = 0
		elif s1[i] == '0' and s2[i] == '0':
			z = z + 1
			if z and o:
				ans = ans + 2
				z = z - 1
				o = 0
		else:
			o = 1
			if z and o:
				ans = ans + 2
				z = 0
				o = 0
	print(ans + z)

def solve4():
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	ans = 0
	for i in range(m):
		for j in range(i):
			if l[j] < l[i]:
				ans = ans + 1
	print(ans)
for testis in range(int(input())):
	solve4()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = sorted(a)
	b = []
	d = {}
	for i in range(n):
		b.append([])
		d[i] = {}
		for j in range(m):
			b[i].append(0)
	j = 0
	for i in range(len(a)):
		b[j][i % m] = 0
		if a[i] in d[j]:
			d[j][a[i]] += 1
		else:
			d[j][a[i]] = 1
		j += 1
		if j == len(b):
			j = 0
	ans = 0
	for i in range(len(b)):
		x = 0
		for j in range(len(b[i])):
			seat = c.index(a[j + i * m])
			if d[i][a[j + i * m]] > 1:
				seat += d[i][a[j + i * m]] - 1
				d[i][a[j + i * m]] -= 1
			b[i][seat] = 1
			for k in range(0, seat):
				if b[i][k] == 1:
					x += 1
		ans += x
	print(ans)


import sys
import getpass
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline
M9 = 10 ** 9 + 7
(yes, no) = ('YES', 'NO')
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [input().strip() for _ in range(rows)]

def minus_one(arr):
	return [x - 1 for x in arr]

def minus_one_matrix(mrr):
	return [[x - 1 for x in row] for row in mrr]

class FenwickTree:

	def __init__(self, bits=31):
		self.c = defaultdict(int)
		self.LARGE = 2 ** bits

	def update(self, x, increment):
		x += 1
		while x <= self.LARGE:
			self.c[x] += increment
			x += x & -x

	def query(self, x):
		x += 1
		res = 0
		while x > 0:
			res += self.c[x]
			x -= x & -x
		return res

def solve_(lst):
	lst = [(x, -i) for (i, x) in enumerate(lst)]
	lst.sort()
	log(lst)
	lst = [(-i, j, x) for (j, (x, i)) in enumerate(lst)]
	lst.sort()
	log(lst)
	f = FenwickTree(bits=10)
	res = 0
	for (i, j, x) in lst:
		val = f.query(j)
		res += val
		f.update(j, 1)
	return res
for case_num in range(int(input())):
	(n, m) = list(map(int, input().split()))
	lst = list(map(int, input().split()))
	res = solve(lst)
	print(res)


def InvCount(arr, n):
	inv_count = 0
	for i in range(n):
		for j in range(i + 1, n):
			if arr[i] > arr[j]:
				inv_count += 1
	return inv_count
for case in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	nums = [int(x) for x in input().split()]
	nums = nums[::-1]
	print(InvCount(nums, m))