Chef Monocarp has just put $n$ dishes into an oven. He knows that the $i$-th dish has its optimal cooking time equal to $t_i$ minutes.

At any positive integer minute $T$ Monocarp can put no more than one dish out of the oven. If the $i$-th dish is put out at some minute $T$, then its unpleasant value is $|T - t_i|$ — the absolute difference between $T$ and $t_i$. Once the dish is out of the oven, it can't go back in.

Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain?


-----Input-----

The first line contains a single integer $q$ ($1 \le q \le 200$) — the number of testcases.

Then $q$ testcases follow.

The first line of the testcase contains a single integer $n$ ($1 \le n \le 200$) — the number of dishes in the oven.

The second line of the testcase contains $n$ integers $t_1, t_2, \dots, t_n$ ($1 \le t_i \le n$) — the optimal cooking time for each dish.

The sum of $n$ over all $q$ testcases doesn't exceed $200$.


-----Output-----

Print a single integer for each testcase — the minimum total unpleasant value Monocarp can obtain when he puts out all the dishes out of the oven. Remember that Monocarp can only put the dishes out at positive integer minutes and no more than one dish at any minute.


-----Example-----
Input
6
6
4 2 4 4 5 2
7
7 7 7 7 7 7 7
1
1
5
5 1 2 4 3
4
1 4 4 4
21
21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13

Output
4
12
0
0
2
21



-----Note-----

In the first example Monocarp can put out the dishes at minutes $3, 1, 5, 4, 6, 2$. That way the total unpleasant value will be $|4 - 3| + |2 - 1| + |4 - 5| + |4 - 4| + |6 - 5| + |2 - 2| = 4$.

In the second example Monocarp can put out the dishes at minutes $4, 5, 6, 7, 8, 9, 10$.

In the third example Monocarp can put out the dish at minute $1$.

In the fourth example Monocarp can put out the dishes at minutes $5, 1, 2, 4, 3$.

In the fifth example Monocarp can put out the dishes at minutes $1, 3, 4, 5$.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Sorting

Greedy algorithms

Dynamic programming

Flows and cuts

Mathematics


Solutions:
import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	T = list(map(int, input().split()))
	T.sort()
	dp = [float('inf')] * (n + 1)
	dp[n] = abs(T[n - 1] - 2 * n)
	for i in range(2 * n - 1, 0, -1):
		for j in range(max(i - n, 1), n):
			dp[j] = min(dp[j], dp[j + 1] + abs(i - T[j - 1]))
		dp[-1] = abs(T[n - 1] - i) if i >= n else float('inf')
	return dp[1]
for _ in range(int(input())):
	print(solve())


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = [0] + a
	a.sort()
	b = [[10000000000 for i in range(2 * n + 1)] for j in range(n + 1)]
	b[0][0] = 0
	mini = 10000000000
	menu = 10000000000
	for i in range(1, n + 1):
		mini = 10000000000
		for j in range(2 * n + 1):
			if j >= i:
				b[i][j] = abs(a[i] - j) + mini
			mini = min(mini, b[i - 1][j])
			if i == n:
				menu = min(menu, b[i][j])
	print(menu)


def hungarian(bipartite_graph):
	infinity = int(10000000.0)
	n_row = len(bipartite_graph)
	n_col = len(bipartite_graph[0])
	u = [0] * n_row
	v = [0] * n_col
	mark_indices = [-1] * n_col
	cost = 0
	for i in range(n_row):
		links = [-1] * n_col
		mins = [infinity] * n_col
		visited = [False] * n_col
		marked_i = i
		marked_j = -1
		j_optimal = -1
		while marked_i != -1:
			j_optimal = -1
			row_delta = infinity
			for j1 in range(n_col):
				if not visited[j1]:
					j_delta = bipartite_graph[marked_i][j1] - u[marked_i] - v[j1]
					if j_delta < mins[j1]:
						mins[j1] = j_delta
						links[j1] = marked_j
					if mins[j1] < row_delta:
						row_delta = mins[j1]
						j_optimal = j1
			for j1 in range(n_col):
				if visited[j1]:
					u[mark_indices[j1]] += row_delta
					v[j1] -= row_delta
				else:
					mins[j1] -= row_delta
			u[i] += row_delta
			cost += row_delta
			visited[j_optimal] = True
			marked_j = j_optimal
			marked_i = mark_indices[j_optimal]
		while links[j_optimal] != -1:
			mark_indices[j_optimal] = mark_indices[links[j_optimal]]
			j_optimal = links[j_optimal]
		mark_indices[j_optimal] = i
	return cost

def process_test_case(i_t):
	n = int(input())
	t_vec = list(map(int, input().split()))
	t_vec.sort()
	dist_mat = [[abs(t - j - 1) for j in range(2 * n)] for t in t_vec]
	answer = hungarian(dist_mat)
	print(answer)
	return None
n_tests = int(input())
for i_test in range(1, n_tests + 1):
	process_test_case(i_test)


q = int(input())
for _ in range(q):
	n = int(input())
	cooking_times = list(map(int, input().split()))
	ct_sorted = sorted(cooking_times)
	min_total_dp = [100000 for _ in range(n + 1)]
	min_total_dp[0] = 0
	for i in range(1, 2 * (n + 1)):
		for j in range(n, 0, -1):
			diff = abs(ct_sorted[j - 1] - i)
			min_total_dp[j] = min(min_total_dp[j], min_total_dp[j - 1] + diff)
	print(min_total_dp[n])


def main():
	nums = int(input())
	a = [int(x) for x in input().split(' ')]
	tb = [[float('inf')] * (nums + 1) for _ in range(2 * nums + 1)]
	a.sort()
	tb[0][0] = 0
	for t in range(1, 2 * nums + 1):
		tb[t][0] = 0
		for n in range(1, nums + 1):
			if n > t:
				break
			get = tb[t - 1][n - 1] + abs(a[n - 1] - t)
			notget = tb[t - 1][n]
			tb[t][n] = min(get, notget)
	rt = [tb[t][nums] for _ in range(len(tb))]
	print(min(rt))
cases = int(input())
for _ in range(cases):
	main()


import sys
import math
from functools import reduce
import bisect

def getN():
	return int(input())

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

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

def input():
	return sys.stdin.readline().rstrip()

def index(a, x):
	i = bisect.bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	return False
for _ in range(getN()):
	n = getN()
	arr = sorted(getList())
	dp = [[float('inf')] * 400 for _ in range(n + 1)]
	dp[0] = [0] * 400
	for i in range(n):
		for j in range(399):
			dp[i + 1][j + 1] = min(dp[i][j] + abs(arr[i] - j - 1), dp[i + 1][j])
	print(dp[-1][-1])


import sys
import math
import collections
import functools

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_input():
	return list(map(int, input().split()))
t = int(input())
for ti in range(1, t + 1):

	@functools.lru_cache(None)
	def dp(i, t):
		if i == n:
			cur = 0
		else:
			cur = float('inf')
			if t == 2 * 200 + 1:
				cur = float('inf')
			else:
				cur = min(cur, dp(i, t + 1))
				cur = min(cur, dp(i + 1, t + 1) + abs(A[i] - t))
		return cur
	n = int(input())
	A = int_input()
	A.sort()
	res = dp(0, 1)
	print(res)


from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	arr.sort()
	dp = [[10 ** 9 for _ in range(2 * n)] for _ in range(n)]
	for i in range(0, n):
		for j in range(1, 2 * n):
			if i == 0:
				dp[i][j] = min(dp[i][j - 1], abs(arr[i] - j))
			else:
				dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] + abs(arr[i] - j))
	print(dp[n - 1][2 * n - 1])


import sys
input = sys.stdin.readline

def main():
	n = int(input())
	tlst = list(map(int, input().split()))
	tlst.sort()
	inf = 10 ** 20
	dp = [[inf for _ in range(2 * n)] for _ in range(n)]
	dp[0][0] = tlst[0]
	for i in range(1, 2 * n):
		dp[0][i] = min(dp[0][i - 1], abs(tlst[0] - i))
	for i in range(1, n):
		for j in range(i + 1, 2 * n):
			dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] + abs(tlst[i] - j))
	print(dp[-1][-1])
for _ in range(int(input())):
	main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[10 ** 9] * (n + 1) for i in range(401)]
	for i in range(401):
		dp[i][0] = 0
	for i in range(1, 401):
		for j in range(1, n + 1):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(a[j - 1] - i), dp[i - 1][j])
	print(dp[-1][-1])


import sys, collections
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort()
	dp = [[float('inf')] * (2 * n + 1) for _ in range(n + 1)]
	for i in range(2 * n + 1):
		dp[0][i] = 0
	for i in range(n):
		for j in range(2 * n):
			dp[i + 1][j + 1] = min(dp[i][j] + abs(A[i] - (j + 1)), dp[i + 1][j])
	print(dp[-1][-1])


INF = float('inf')
for _ in range(int(input())):
	n = int(input())
	a = sorted(map(int, input().split()))
	dp = [[INF] * (2 * n + 1) for _ in range(n + 1)]
	for j in range(2 * n + 1):
		dp[0][j] = 0
	for i in range(n):
		for j in range(2 * n):
			dp[i + 1][j + 1] = min(dp[i][j] + abs(a[i] - (j + 1)), dp[i + 1][j])
	print(dp[-1][-1])


t = int(input())
ans = [0] * t
for _ in range(t):
	n = int(input())
	a = sorted(map(int, input().split()))
	inf = 10 ** 9
	dp = [[inf] * (n + 100) for _ in range(n + 1)]
	dp[0] = [0] * (n + 100)
	for i in range(n):
		cost = dp[i][0]
		for t in range(1, n + 100):
			dp[i + 1][t] = min(dp[i + 1][t], cost + abs(a[i] - t))
			cost = min(cost, dp[i][t])
	ans[_] = min(dp[-1])
print(*ans, sep='\n')


q = int(input())
for _ in range(q):
	n = int(input())
	inf = 10 ** 6
	t = sorted(list(map(int, input().split())))
	d = [[0] * (2 * n + 1) for i in range(n)]
	d[0][0] = abs(t[0] - 1)
	for i in range(n):
		for j in range(1, 2 * n + 1):
			if i == 0 and j > 0:
				d[i][j] = min(abs(t[0] - j), d[i][j - 1])
			elif i >= j:
				d[i][j] = inf
			else:
				d[i][j] = min(d[i - 1][j - 1] + abs(t[i] - j), d[i][j - 1])
	print(d[n - 1][2 * n])


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

def prog():
	for _ in range(int(input())):
		n = int(input())
		t = Counter(list(map(int, input().split())))
		dishes = []
		for i in t:
			dishes.append([i, t[i]])
		dishes.sort()
		ans = 10 ** 9
		dp = [[10 ** 9] * (2 * n + 1) for i in range(len(dishes) + 1)]
		dp[0] = [0] * (2 * n + 1)
		for dish in range(len(dishes)):
			amt = dishes[dish][1]
			m = dishes[dish][0]
			for right in range(dishes[dish][1], 2 * n + 1):
				left = right - amt + 1
				if right < m:
					dp[dish + 1][right] = min(dp[dish + 1][right - 1], dp[dish][left - 1] + (m - left) * (m - left + 1) // 2 - (m - right - 1) * (m - right) // 2)
				elif left > m:
					dp[dish + 1][right] = min(dp[dish + 1][right - 1], dp[dish][left - 1] + (right - m) * (right - m + 1) // 2 - (left - m - 1) * (left - m) // 2)
				else:
					dp[dish + 1][right] = min(dp[dish + 1][right - 1], dp[dish][left - 1] + (right - m) * (right - m + 1) // 2 + (m - (right - amt + 1)) * (m - (right - amt + 1) + 1) // 2)
		print(dp[len(dishes)][2 * n])
prog()


def solve(arr, n, ans):
	arr.sort()
	T = max(n, max(arr))
	dp = [[float('inf') for k in range(2 * T + 5)] for i in range(n + 1)]
	dp[0][0] = 0
	for pos in range(1, n + 1):
		for last_time in range(2 * T + 5):
			for time in range(last_time + 1, 2 * T + 5):
				dp[pos][time] = min(dp[pos][time], dp[pos - 1][last_time] + abs(time - arr[pos - 1]))
	ans.append(str(min(dp[-1])))

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(arr, n, ans)
	print('\n'.join(ans))
main()


def read_int() -> int:
	return int(input())

def read_ints():
	return map(int, input().split(' '))
INF = 9999999999

def test_case():
	n = read_int()
	t = sorted(read_ints())
	dp = [[INF if i != 0 else 0 for _ in range(2 * n + 1)] for i in range(n + 1)]
	for dish_index in range(1, n + 1):
		for minute in range(1, 2 * n + 1):
			dp[dish_index][minute] = min((x for (index, x) in enumerate(dp[dish_index - 1]) if index < minute)) + abs(t[dish_index - 1] - minute)
	print(min(dp[n]))
for _ in range(read_int()):
	test_case()


import sys, os.path
from collections import *
from heapq import *
from copy import *
import math
mod = 10 ** 9 + 7
read = lambda : map(int, input().split())
inf = sys.maxsize
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[-1 for i in range(405)] for j in range(200)]

	def solve(ind, t):
		if ind == n:
			return 0
		if t == 2 * n + 1:
			return 10 ** 9
		if dp[ind][t] != -1:
			return dp[ind][t]
		ans = inf
		ans = min(ans, solve(ind, t + 1))
		ans = min(ans, abs(t - a[ind]) + solve(ind + 1, t + 1))
		dp[ind][t] = ans
		return dp[ind][t]
	print(solve(0, 1))


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations, combinations

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

def mdata():
	return list(map(int, data().split()))

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

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 9
mod = int(1000000000.0) + 7
for q in range(int(data())):
	n = int(data())
	t = mdata()
	t.sort()
	dp = [[0] * 301 for i in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(i, 301):
			dp[i][j] = min(dp[i - 1][i - 1:j]) + abs(j - t[i - 1])
	out(min(dp[-1][n:]))


from functools import lru_cache
q = int(input())
for _ in range(q):
	n = int(input())
	t = [int(x) for x in input().split()]
	t.sort()
	MAXT = n + (n + 2) // 2

	@lru_cache(None)
	def dp(idx, time):
		if idx == 0 and time == 1:
			return abs(t[0] - 1)
		if time < 1:
			return float('inf')
		if idx < 0:
			return 0
		return min(dp(idx - 1, time - 1) + abs(t[idx] - time), dp(idx, time - 1))
	print(dp(n - 1, MAXT))


MAXT = 400

def f(l):
	n = len(l)
	l.sort()
	dp = [0] * (MAXT + 1)
	for i in range(1, n + 1):
		t = l[i - 1]
		dpold = [i for i in dp]
		dp[i] = dpold[i - 1] + abs(i - t)
		for j in range(i + 1, MAXT + 1):
			dp[j] = min(dp[j - 1], dpold[j - 1] + abs(t - j))
	return min(dp[n:])
q = int(input())
for _ in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	print(f(l))


N = 402

def solve(n, a):
	a.sort()
	dp = [[float('inf')] * N for _ in range(N)]
	dp[0][0] = 0
	for i in range(n + 1):
		for x in range(2 * n):
			dp[i][x + 1] = min(dp[i][x + 1], dp[i][x])
			if i < n:
				dp[i + 1][x + 1] = min(dp[i + 1][x + 1], dp[i][x] + abs(a[i] - (x + 1)))
	return dp[n][2 * n]
t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	print(solve(n, a))
	t -= 1


from math import inf, log2

class SegmentTree:

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

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

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

	def update(self, index, value):
		index += self.size
		self.data[index] = value
		index >>= 1
		while index:
			self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1])
			index >>= 1
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	dp = [[inf] * (n + 1) for __ in range(501)]
	dp[0][0] = 0
	for j in range(n):
		for i in range(500):
			dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(a[j] - (i + 1)))
			dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
	print(min((x[-1] for x in dp)))


for _ in range(int(input())):
	n = int(input())
	t = sorted(list(map(int, input().split())))
	m = max(max(t) * 2, n + 1)
	dp = [[100000000] * (m + 1) for i in range(n)]
	for j in range(1, m + 1):
		dp[0][j] = abs(t[0] - j)
	for i in range(1, n):
		for j in range(2, m + 1):
			if i <= j:
				dp[i][j] = abs(t[i] - j) + min(dp[i - 1][:j])
	print(min(dp[-1]))


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(*t,) = map(int, input().split())
	t.sort()
	dp = [[0] * (3 * n) for _ in range(n)]
	dp[0] = [100000000000] + [abs(t[0] - i) for i in range(1, 3 * n)]
	for i in range(1, n):
		for j in range(i + 1, 3 * n):
			dp[i][j] = 1000000000
			for k in range(i, j):
				dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(t[i] - j))
	print(min(dp[n - 1][n:]))


import sys
import math
from collections import Counter

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

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

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

def SI():
	return sys.stdin.readline().strip()
t = II()
for j in range(t):
	n = II()
	s = LI()
	s.sort()
	dp = [[2 ** 31 for i in range(2 * n + 1)] for j in range(n)]
	mn = 2 ** 31
	for k in range(1, 2 * n + 1):
		dp[0][k] = min(abs(k - s[0]), mn)
		mn = dp[0][k]
	for i in range(1, n):
		for k in range(1, 2 * n + 1):
			dp[i][k] = min(dp[i - 1][k - 1] + abs(s[i] - k), dp[i][k - 1])
	print(dp[n - 1][2 * n])


for _ in range(int(input())):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	dp = [[float('inf')] * (n + 1) for i in range(2 * n + 1)]
	for i in range(n + 1):
		dp[i][0] = 0
	for i in range(1, 2 * n + 1):
		for j in range(1, n + 1):
			dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1] + abs(i - t[j - 1]))
	print(dp[2 * n][n])


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[100000 for j in range(2 * n + 2)] for k in range(n + 1)]
	for j in range(2 * n + 2):
		dp[0][j] = 0
	for j in range(1, n + 1):
		for k in range(j, 2 * n + 2):
			dp[j][k] = min(dp[j][k], dp[j][k - 1], dp[j - 1][k - 1] + abs(k - a[j - 1]))
	print(dp[-1][-1])


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	dp = [[float('inf') for i in range(2 * n + 1)] for i in range(n)]
	for i in range(1, 2 * n + 1):
		dp[0][i] = min(abs(a[0] - i), dp[0][i - 1])
	for i in range(1, n):
		for time in range(1, 2 * n + 1):
			dp[i][time] = min(abs(a[i] - time) + dp[i - 1][time - 1], dp[i][time - 1])
	print(dp[n - 1][2 * n])


inf = 10 ** 10

def solve():
	n = int(input())
	food = list(map(int, input().split()))
	food.sort()
	dp = [[inf] * (n + 199) for i in range(n + 1)]
	dp[0][0] = 0
	for (i, v) in enumerate(food):
		for k in range(n + 199):
			for m in range(k):
				dp[i + 1][k] = min(dp[i + 1][k], dp[i][m] + abs(k - v))
	ans = min((dp[n][j] for j in range(n + 199)))
	print(ans)
	return

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


def helper(idx, T, n, a, dp):
	if idx == n:
		return 0
	if T == 2 * n + 1:
		return 100000000.0
	if dp[idx][T] != -1:
		return dp[idx][T]
	ans = float('inf')
	ans = min(ans, helper(idx, T + 1, n, a, dp))
	ans = min(ans, abs(a[idx] - T) + helper(idx + 1, T + 1, n, a, dp))
	dp[idx][T] = ans
	return ans

def solve(n, a, dp):
	return helper(0, 1, n, a, dp)
t = int(input())
n = 0
a = None
while t:
	dp = [[-1] * 402 for _ in range(402)]
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	print(solve(n, a, dp))
	t -= 1


import sys
from collections import deque
from copy import *
from itertools import permutations as prm, product

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def string(s):
	return ''.join(s)

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

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

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

def isvalid(i, j, n, m):
	return 0 <= i < n and 0 <= j < m

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
while t > 0:
	t -= 1
	n = fi()
	a = li()
	d = {}
	ans = 0
	vis = {}
	a.sort()
	mini = 10 ** 18
	dp = [[10 ** 18] * 405 for i in range(n + 1)]
	for i in range(n):
		for j in range(1, 405):
			if i == 0:
				dp[i][j] = abs(a[i] - j)
			else:
				dp[i][j] = min(dp[i - 1][:j]) + abs(a[i] - j)
	print(min(dp[n - 1]))


def solve(index, time, ar, dp):
	if index == len(ar):
		return 0
	if time == 2 * len(ar) + 1:
		return pow(10, 8)
	if dp[index][time] != -1:
		return dp[index][time]
	dp[index][time] = min(solve(index, time + 1, ar, dp), abs(time - ar[index]) + solve(index + 1, time + 1, ar, dp))
	return dp[index][time]
for _ in range(int(input())):
	n = int(input())
	ar = [int(i) for i in input().split()]
	ar.sort()
	dp = [[-1 for i in range(2 * n + 1)] for i in range(n + 1)]
	print(solve(0, 1, ar, dp))


q = int(input())
while q:
	q -= 1
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort()
	dp = [[float('inf') for x in range(2 * n + 1)] for x in range(n + 1)]
	for t in range(2 * n + 1):
		dp[0][t] = 0
	for i in range(1, n + 1):
		for t in range(1, 2 * n + 1):
			dp[i][t] = min(dp[i][t], dp[i][t - 1])
			dp[i][t] = min(dp[i][t], dp[i - 1][t - 1] + abs(arr[i - 1] - t))
	a = float('inf')
	for i in range(2 * n + 1):
		a = min(a, dp[n][i])
	print(a)


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

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

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

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from functools import lru_cache
for _ in range(N()):
	n = N()
	a = [0] + RLL()
	a.sort()

	@lru_cache(50000)
	def find(t, s):
		if s == n + 1:
			return 0
		res = find(t + 1, s + 1) + abs(t - a[s])
		for i in range(t + 1, a[s] + 1):
			res = min(res, find(i + 1, s + 1) + abs(i - a[s]))
		return res
	print(find(1, 1))


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
inf = 10 ** 16
for _ in range(II()):
	n = II()
	tt = LI()
	tt.sort()
	dp = [inf] * (2 * n + 1)
	dp[0] = 0
	for t in tt:
		ndp = [inf] * (2 * n + 1)
		mn = inf
		for i in range(1, 2 * n + 1):
			mn = min(mn, dp[i - 1])
			ndp[i] = mn + abs(i - t)
		dp = ndp
	print(min(dp))


q = int(input().strip())
for _ in range(q):
	n = int(input().strip())
	t = [int(_) for _ in input().strip().split()]
	t.sort()
	N = t[-1] + n
	d0 = [max(t[0] - x, 0) for x in range(N)]
	d0[0] = [-1]
	d = [d0]
	for i in range(1, n):
		d += [[-1] * len(d0)]
		for j in range(i + 1, N):
			d[i][j] = d[i - 1][j - 1] + abs(t[i] - j)
			if d[i][j - 1] >= 0:
				d[i][j] = min(d[i][j], d[i][j - 1])
	ans = d[n - 1][N - 1]
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr = sorted(arr)
	dp = [[float('inf') for j in range(2 * n)] for i in range(n + 1)]
	for i in range(2 * n):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for j in range(i, 2 * n):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(j - arr[i - 1]), dp[i][j - 1])
	print(dp[n][-1])


from math import inf
q = int(input())
arr = []
for _ in range(q):
	n = int(input())
	arr.append(sorted(list(map(int, input().split()))))
for nums in arr:
	dp = [[inf] * (2 * len(nums)) for _ in range(len(nums))]
	pretemp = []
	for T in range(2 * len(nums)):
		dp[0][T] = abs(nums[0] - (T + 1))
		if len(pretemp) == 0:
			pretemp.append(dp[0][T])
		else:
			pretemp.append(min(pretemp[-1], dp[0][T]))
	for i in range(1, len(nums)):
		temp = []
		for T in range(i, 2 * len(nums)):
			dp[i][T] = abs(nums[i] - (T + 1)) + pretemp[T - i]
			temp.append(dp[i][T])
		pretemp = temp[:]
		for i in range(1, len(temp)):
			pretemp[i] = min(pretemp[i - 1], pretemp[i])
	print(min(dp[-1]))


import os
from heapq import heapify, heappop, heappush
import sys
import sys, threading
import math
import operator
import bisect
from collections import defaultdict
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		ar = inpt()
		ar.sort()
		for i in range(n):
			ar[i] -= 1
		dp = []
		for _ in range(n + 1):
			dp.append([10 ** 9] * (2 * n))
		dp[0][0] = 0
		for i in range(n + 1):
			for j in range(0, 2 * n - 1):
				if dp[i][j] < 10 ** 9:
					if i < n:
						dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(ar[i] - j))
					dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
		print(dp[n][2 * n - 1])
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 sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
mod = 10 ** 9 + 7
INF = float('inf')

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

def inpl():
	return list(map(int, sys.stdin.readline().split()))
for _ in range(inp()):
	n = inp()
	a = inpl()
	a.sort()
	mx = max(a) + n + 100
	dp = [[INF] * mx for _ in range(n + 1)]
	dp[0][0] = 0
	for i in range(n):
		for j in range(mx):
			for k in range(j + 1, mx):
				dp[i + 1][k] = min(dp[i + 1][k], dp[i][j] + abs(a[i] - k))
	print(min(dp[-1]))


for df in range(int(input())):
	n = int(input())
	s = sorted(list(map(int, input().split())))
	dp = [[0 for j in range(2 * n + 1)] for i in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(i, 2 * n + 1):
			dp[i][j] = dp[i - 1][j - 1] + abs(s[i - 1] - j)
			if j > i and dp[i][j] > dp[i][j - 1]:
				dp[i][j] = dp[i][j - 1]
	print(dp[n][2 * n])


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	T = sorted(map(int, input().split()))
	DP = [1 << 31] * (2 * n + 1)
	for i in range(1, 2 * n + 1):
		DP[i] = abs(T[0] - i)
	for i in range(1, n):
		NDP = [1 << 31] * (2 * n + 1)
		for j in range(1, 2 * n + 1):
			f = DP[j]
			for k in range(j + 1, 2 * n + 1):
				NDP[k] = min(NDP[k], f + abs(T[i] - k))
		DP = NDP
	print(min(DP))


import sys, os
from io import BytesIO, IOBase
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
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')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
tc = 1
tc = int(input())
for test in range(1, tc + 1):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	dp = [[float('inf')] * (n + 1) for i in range(2 * n + 1)]
	for i in range(n + 1):
		dp[i][0] = 0
	for i in range(1, 2 * n + 1):
		for j in range(1, n + 1):
			dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1] + abs(i - t[j - 1]))
	print(dp[2 * n][n])


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	dp = [[float('inf')] * 401 for _ in range(n + 5)]
	for i in range(n):
		for j in range(1, 401):
			if i == 0:
				dp[i][j] = abs(l[i] - j)
			else:
				dp[i][j] = min(dp[i - 1][:j]) + abs(l[i] - j)
	print(min(dp[n - 1]))


import sys as _sys

def main():
	q = int(input())
	for i_q in range(q):
		(n,) = _read_ints()
		field = [0] * n + [0] * n
		for t in _read_ints():
			field[t - 1] += 1
		zeros_indices = []
		wrong_indices = []
		for (i, x) in enumerate(field):
			if x == 0:
				zeros_indices.append(i)
			while field[i] > 1:
				wrong_indices.append(i)
				field[i] -= 1
		cache = dict()

		def f(i_i_first_zero, i_i_first_wrong):
			key = (i_i_first_zero, i_i_first_wrong)
			if key in cache:
				return cache[key]
			if i_i_first_wrong == len(wrong_indices):
				return 0
			if i_i_first_zero == len(zeros_indices):
				return float('inf')
			i_first_wrong = wrong_indices[i_i_first_wrong]
			result = float('inf')
			is_first_iter = True
			while is_first_iter or zeros_indices[i_i_first_zero - 1] < i_first_wrong:
				result = min(result, f(i_i_first_zero + 1, i_i_first_wrong + 1) + abs(i_first_wrong - zeros_indices[i_i_first_zero]))
				i_i_first_zero += 1
				is_first_iter = False
			cache[key] = result
			return result
		result = f(0, 0)
		print(result)

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return map(int, _read_line().split())
main()


t = int(input())
while t:
	n = int(input())
	a = [0] + list(map(int, input().split()))
	dp = [[1e+20 for j in range(n + 1)] for i in range(2 * n + 1)]
	a.sort()
	dp[1][1] = a[1] - 1
	for i in range(2, 2 * n + 1):
		dp[i][1] = min(abs(a[1] - i), dp[i - 1][1])
	for i in range(2, 2 * n + 1):
		for j in range(2, min(i + 1, n + 1)):
			dp[i][j] = min(dp[i - 1][j], abs(i - a[j]) + dp[i - 1][j - 1])
	print(dp[2 * n][n])
	t -= 1


for _ in range(int(input())):
	n = int(input())
	p = [int(x) for x in input().split()]
	p.sort()
	d = [[200 * 200 + 1 for i in range(n + 1)] for j in range(2 * (n + 1))]
	d[0][0] = 0
	for i in range(0, n):
		d[i][0] = 0
	for j in range(1, n + 1):
		for i in range(1, 2 * n + 2):
			d[i][j] = min(d[i - 1][j], d[i - 1][j - 1] + abs(p[j - 1] - i))
	print(d[2 * n + 1][n])


a = int(input())
b = 0
arr = []
summ = 0
dpp = []

def dp(i, t):
	if i == len(arr):
		return summ
	if t >= 2 * b:
		return float('inf')
	if dpp[i][t] == -1:
		dpp[i][t] = min(dp(i + 1, t + 1) + abs(arr[i] - t), dp(i, t + 1))
	return dpp[i][t]
for i in range(a):
	b = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	dpp = [[-1 for i in range(400)] for j in range(len(arr) + 1)]
	print(dp(0, 1))


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	nums = list(map(int, stdin.readline().split()))
	nums.sort()
	dp = [[float('inf')] * (2 * n + 1) for _ in range(n + 1)]
	dp[0][0] = 0
	for i in range(n + 1):
		for j in range(2 * n):
			if i < n:
				dp[i + 1][j + 1] = min(dp[i][j] + abs(nums[i] - (j + 1)), dp[i + 1][j + 1])
			dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	print(dp[n][2 * n])


from sys import stdin
nii = lambda : map(int, stdin.readline().split())
lnii = lambda : list(map(int, stdin.readline().split()))
q = int(input())
for qq in range(q):
	n = int(input())
	t = lnii()
	t.sort()
	dp = [[float('inf') for i in range(2 * n + 1)] for j in range(n + 1)]
	for i in range(2 * n + 1):
		dp[0][i] = 0
	for i in range(n):
		for j in range(2 * n):
			dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j] + abs(j + 1 - t[i]))
	print(dp[-1][-1])


import sys, math, itertools, collections, copy
input = sys.stdin.readline
INF = 10 ** 18 + 20

def solve():
	N = int(input())
	t = [int(x) for x in input().split()]
	t.sort()
	dp = [[INF for j in range(N)] for i in range(2 * N + 1)]
	for i in range(1, 2 * N + 1):
		for j in range(N):
			if j > i:
				break
			if i == 0:
				dp[i][j] = min(dp[i][j], abs(t[j] - i))
			elif j > 0:
				dp[i][j] = min(dp[i][j], dp[i - 1][j], dp[i - 1][j - 1] + abs(t[j] - i))
			else:
				dp[i][j] = min(dp[i][j], dp[i - 1][j], abs(t[j] - i))
	print(dp[-1][-1])
for _ in range(int(input())):
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	d = [float('inf')] * (n + 1)
	d[0] = 0
	for j in range(1, 2 * n + 1):
		for k in range(n, 0, -1):
			d[k] = min(d[k], d[k - 1] + abs(l[k - 1] - j))
	print(d[n])


import sys, os, io
input = sys.stdin.readline
T = int(input())
ans = [0] * T
from collections import Counter
for t in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	c = Counter(A)
	dp = [[float('inf')] * 401 for _ in range(201)]
	dp[0] = [0] * 201
	for i in range(1, 201):
		if c[i] == 0:
			dp[i] = dp[i - 1]
			continue
		cnt = 0
		for p in range(1, c[i] + 1):
			cnt += abs(p - i)
		for j in range(c[i], 401):
			dp[i][j] = min(dp[i - 1][:j - c[i] + 1]) + cnt
			cnt -= abs(i - (j - c[i] + 1))
			cnt += abs(j + 1 - i)
	ans[t] = min(dp[200])
print(*ans, sep='\n')


q = int(input())
for _ in range(q):
	n = int(input())
	t = [int(x) for x in input().split()]
	t.sort()
	N = n + n // 1 + 2
	dp = [[float('inf') for _a in range(N)] for __ in range(n)]
	for i in range(n):
		for time in range(1, N):
			if i == 0 and time == 1:
				dp[i][time] = abs(t[i] - time)
			elif i == 0:
				dp[i][time] = min(abs(t[i] - time), dp[i][time - 1])
			elif time == 1:
				continue
			else:
				dp[i][time] = min(dp[i - 1][time - 1] + abs(t[i] - time), dp[i][time - 1])
	ans = float('inf')
	for time in range(1, N):
		ans = min(ans, dp[n - 1][time])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	dp = [[0] * (2 * n + 1) for i in range(n + 1)]
	min_dp = [0] * (2 * n + 1)
	for i in range(1, n + 1):
		for T in range(i, 2 * n + 1):
			dp[i][T] = min(dp[i - 1][i - 1:T]) + abs(T - t[i - 1])
	print(min(dp[n][n:]))


from math import *
import threading
import sys
mod = 10 ** 9 + 7

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

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

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

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

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

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

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

def graph(n, m):
	adj = dict()
	for i in range(1, n + 1):
		adj.setdefault(i, 0)
	for i in range(m):
		(a, b) = map(int, input().split())
		adj[a] += 1
		adj[b] += 1
	return adj

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

def fn(n):
	i = 2
	res = n - 1
	val = 0
	for i in range(int(sqrt(n)) + 1, 1, -1):
		val = i - 1 + int(ceil((n - i) / i))
		if val <= res:
			res = val
		else:
			break
	return res

def solve(a, b, c):
	dis = b ** 2 - 4 * a * c
	ans1 = (-b - sqrt(dis)) / (2 * a)
	print(int(ans1))
	return
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[inf] * (n + 1) for i in range(401)]
	for i in range(401):
		dp[i][0] = 0
	for i in range(1, 401):
		for j in range(1, n + 1):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(a[j - 1] - i), dp[i - 1][j])
	print(dp[-1][-1])


import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

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

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

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

def pr(n):
	return sys.stdout.write(str(n) + '\n')

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():

	def help(i, j):
		if i >= n:
			return 0
		if j > 2 * n:
			return INF
		if (i, j) in d:
			return d[i, j]
		cur = min(abs(l[i] - j) + help(i + 1, j + 1), help(i, j + 1))
		d[i, j] = cur
		return cur
	d = defaultdict(int)
	n = inp()
	l = li()
	l.sort()
	pr(help(0, 1))
for _ in range(inp()):
	solve()


def solve(lst, pos, time, cache):
	if pos >= len(lst):
		return 0
	if (pos, time) in cache:
		return cache[pos, time]
	if lst[pos] > time:
		bestValue = min((abs(t - lst[pos]) + solve(lst, pos + 1, t + 1, cache) for t in range(time, lst[pos] + 1)))
	else:
		bestValue = abs(time - lst[pos]) + solve(lst, pos + 1, time + 1, cache)
	cache[pos, time] = bestValue
	return bestValue

def readinput():
	tc = int(input())
	for _ in range(tc):
		cache = {}
		time = int(input())
		nums = list(map(int, input().split(' ')))
		nums.sort()
		print(solve(nums, 0, 1, cache))
readinput()


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

def str(x=b''):
	return x if type(x) is bytes else _str(x).encode()

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 inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())
__docformat__ = 'markdown'
import sys
import copy
from typing import Union, NewType, Sequence, Tuple, Optional, Callable
__all__ = ['Munkres', 'make_cost_matrix', 'DISALLOWED']
AnyNum = NewType('AnyNum', Union[int, float])
Matrix = NewType('Matrix', Sequence[Sequence[AnyNum]])
__version__ = '1.1.4'
__author__ = 'Brian Clapper, bmc@clapper.org'
__url__ = 'https://software.clapper.org/munkres/'
__copyright__ = '(c) 2008-2020 Brian M. Clapper'
__license__ = 'Apache Software License'

class DISALLOWED_OBJ(object):
	pass
DISALLOWED = DISALLOWED_OBJ()
DISALLOWED_PRINTVAL = 'D'

class UnsolvableMatrix(Exception):
	pass

class Munkres:

	def __init__(self):
		self.C = None
		self.row_covered = []
		self.col_covered = []
		self.n = 0
		self.Z0_r = 0
		self.Z0_c = 0
		self.marked = None
		self.path = None

	def pad_matrix(self, matrix: Matrix, pad_value: int=0) -> Matrix:
		max_columns = 0
		total_rows = len(matrix)
		for row in matrix:
			max_columns = max(max_columns, len(row))
		total_rows = max(max_columns, total_rows)
		new_matrix = []
		for row in matrix:
			row_len = len(row)
			new_row = row[:]
			if total_rows > row_len:
				new_row += [pad_value] * (total_rows - row_len)
			new_matrix += [new_row]
		while len(new_matrix) < total_rows:
			new_matrix += [[pad_value] * total_rows]
		return new_matrix

	def compute(self, cost_matrix: Matrix) -> Sequence[Tuple[int, int]]:
		self.C = self.pad_matrix(cost_matrix)
		self.n = len(self.C)
		self.original_length = len(cost_matrix)
		self.original_width = len(cost_matrix[0])
		self.row_covered = [False for i in range(self.n)]
		self.col_covered = [False for i in range(self.n)]
		self.Z0_r = 0
		self.Z0_c = 0
		self.path = self.__make_matrix(self.n * 2, 0)
		self.marked = self.__make_matrix(self.n, 0)
		done = False
		step = 1
		steps = {1: self.__step1, 2: self.__step2, 3: self.__step3, 4: self.__step4, 5: self.__step5, 6: self.__step6}
		while not done:
			try:
				func = steps[step]
				step = func()
			except KeyError:
				done = True
		results = []
		for i in range(self.original_length):
			for j in range(self.original_width):
				if self.marked[i][j] == 1:
					results += [(i, j)]
		return results

	def __copy_matrix(self, matrix: Matrix) -> Matrix:
		return copy.deepcopy(matrix)

	def __make_matrix(self, n: int, val: AnyNum) -> Matrix:
		matrix = []
		for i in range(n):
			matrix += [[val for j in range(n)]]
		return matrix

	def __step1(self) -> int:
		C = self.C
		n = self.n
		for i in range(n):
			vals = [x for x in self.C[i] if x is not DISALLOWED]
			if len(vals) == 0:
				raise UnsolvableMatrix('Row {0} is entirely DISALLOWED.'.format(i))
			minval = min(vals)
			for j in range(n):
				if self.C[i][j] is not DISALLOWED:
					self.C[i][j] -= minval
		return 2

	def __step2(self) -> int:
		n = self.n
		for i in range(n):
			for j in range(n):
				if self.C[i][j] == 0 and (not self.col_covered[j]) and (not self.row_covered[i]):
					self.marked[i][j] = 1
					self.col_covered[j] = True
					self.row_covered[i] = True
					break
		self.__clear_covers()
		return 3

	def __step3(self) -> int:
		n = self.n
		count = 0
		for i in range(n):
			for j in range(n):
				if self.marked[i][j] == 1 and (not self.col_covered[j]):
					self.col_covered[j] = True
					count += 1
		if count >= n:
			step = 7
		else:
			step = 4
		return step

	def __step4(self) -> int:
		step = 0
		done = False
		row = 0
		col = 0
		star_col = -1
		while not done:
			(row, col) = self.__find_a_zero(row, col)
			if row < 0:
				done = True
				step = 6
			else:
				self.marked[row][col] = 2
				star_col = self.__find_star_in_row(row)
				if star_col >= 0:
					col = star_col
					self.row_covered[row] = True
					self.col_covered[col] = False
				else:
					done = True
					self.Z0_r = row
					self.Z0_c = col
					step = 5
		return step

	def __step5(self) -> int:
		count = 0
		path = self.path
		path[count][0] = self.Z0_r
		path[count][1] = self.Z0_c
		done = False
		while not done:
			row = self.__find_star_in_col(path[count][1])
			if row >= 0:
				count += 1
				path[count][0] = row
				path[count][1] = path[count - 1][1]
			else:
				done = True
			if not done:
				col = self.__find_prime_in_row(path[count][0])
				count += 1
				path[count][0] = path[count - 1][0]
				path[count][1] = col
		self.__convert_path(path, count)
		self.__clear_covers()
		self.__erase_primes()
		return 3

	def __step6(self) -> int:
		minval = self.__find_smallest()
		events = 0
		for i in range(self.n):
			for j in range(self.n):
				if self.C[i][j] is DISALLOWED:
					continue
				if self.row_covered[i]:
					self.C[i][j] += minval
					events += 1
				if not self.col_covered[j]:
					self.C[i][j] -= minval
					events += 1
				if self.row_covered[i] and (not self.col_covered[j]):
					events -= 2
		if events == 0:
			raise UnsolvableMatrix('Matrix cannot be solved!')
		return 4

	def __find_smallest(self) -> AnyNum:
		minval = sys.maxsize
		for i in range(self.n):
			for j in range(self.n):
				if not self.row_covered[i] and (not self.col_covered[j]):
					if self.C[i][j] is not DISALLOWED and minval > self.C[i][j]:
						minval = self.C[i][j]
		return minval

	def __find_a_zero(self, i0: int=0, j0: int=0) -> Tuple[int, int]:
		row = -1
		col = -1
		i = i0
		n = self.n
		done = False
		while not done:
			j = j0
			while True:
				if self.C[i][j] == 0 and (not self.row_covered[i]) and (not self.col_covered[j]):
					row = i
					col = j
					done = True
				j = (j + 1) % n
				if j == j0:
					break
			i = (i + 1) % n
			if i == i0:
				done = True
		return (row, col)

	def __find_star_in_row(self, row: Sequence[AnyNum]) -> int:
		col = -1
		for j in range(self.n):
			if self.marked[row][j] == 1:
				col = j
				break
		return col

	def __find_star_in_col(self, col: Sequence[AnyNum]) -> int:
		row = -1
		for i in range(self.n):
			if self.marked[i][col] == 1:
				row = i
				break
		return row

	def __find_prime_in_row(self, row) -> int:
		col = -1
		for j in range(self.n):
			if self.marked[row][j] == 2:
				col = j
				break
		return col

	def __convert_path(self, path: Sequence[Sequence[int]], count: int) -> None:
		for i in range(count + 1):
			if self.marked[path[i][0]][path[i][1]] == 1:
				self.marked[path[i][0]][path[i][1]] = 0
			else:
				self.marked[path[i][0]][path[i][1]] = 1

	def __clear_covers(self) -> None:
		for i in range(self.n):
			self.row_covered[i] = False
			self.col_covered[i] = False

	def __erase_primes(self) -> None:
		for i in range(self.n):
			for j in range(self.n):
				if self.marked[i][j] == 2:
					self.marked[i][j] = 0

def make_cost_matrix(profit_matrix: Matrix, inversion_function: Optional[Callable[[AnyNum], AnyNum]]=None) -> Matrix:
	if not inversion_function:
		maximum = max((max(row) for row in profit_matrix))
		inversion_function = lambda x: maximum - x
	cost_matrix = []
	for row in profit_matrix:
		cost_matrix.append([inversion_function(value) for value in row])
	return cost_matrix

def print_matrix(matrix: Matrix, msg: Optional[str]=None) -> None:
	import math
	if msg is not None:
		print(msg)
	width = 0
	for row in matrix:
		for val in row:
			if val is DISALLOWED:
				val = DISALLOWED_PRINTVAL
			width = max(width, len(str(val)))
	format = '%%%d' % width
	for row in matrix:
		sep = '['
		for val in row:
			if val is DISALLOWED:
				val = DISALLOWED_PRINTVAL
			formatted = (format + 's') % val
			sys.stdout.write(sep + formatted)
			sep = ', '
		sys.stdout.write(']\n')
INF = 487639487

def solve():
	n = itg()
	max_t = int(n * 1.5) + 7
	matrix = [[INF] * n for _ in range(max_t)]
	for (i, t) in enumerate(mpint()):
		for T in range(1, max_t):
			matrix[T][i] = abs(t - T)
	indexes = Munkres().compute(matrix)
	total_cost = 0
	for (r, c) in indexes:
		x = matrix[r][c]
		total_cost += x
	return total_cost

def main():
	for _ in range(itg()):
		print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1437/problem/C'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
elif DEBUG == 2:
	main()
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	main()


test_num = int(input())
while test_num:
	test_num -= 1
	n = int(input())
	t = [int(time) for time in input().split()]
	t.sort()
	dp = [[float('inf') for i in range(2 * n + 1)] for j in range(n + 1)]
	for i in range(2 * n + 1):
		dp[0][i] = 0
	for j in range(1, 2 * n + 1):
		for i in range(n, 0, -1):
			op1 = dp[i][j - 1]
			op2 = dp[i - 1][j - 1] + abs(t[i - 1] - j)
			dp[i][j] = min(op1, op2)
	print(dp[n][2 * n])


import sys

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

def list2d(a, b, c):
	return [[c for j in range(b)] for i in range(a)]

def list3d(a, b, c, d):
	return [[[d for k in range(c)] for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** (-10)
for _ in range(INT()):
	N = INT()
	A = LIST()
	A.sort()
	dp = list2d(N + 1, N * 2 + 1, INF)
	dp[0][0] = 0
	for i in range(N):
		for j in range(N * 2 + 1):
			for k in range(j + 1, N * 2 + 1):
				dp[i + 1][k] = min(dp[i + 1][k], dp[i][j] + abs(A[i] - k))
	ans = min(dp[N])
	print(ans)


from sys import stdin, stdout
from math import factorial as f
for _ in range(int(input())):
	n = int(input())
	t = sorted(map(int, input().split()))
	dp = [[0 for j in range(2 * n)] for i in range(n)]
	for i in range(n):
		for j in range(2 * n):
			if not j:
				dp[i][j] = 100000000
				continue
			if not i:
				if j < t[i]:
					dp[i][j] = abs(t[i] - j)
				continue
			dp[i][j] = min(dp[i][j - 1], abs(t[i] - j) + dp[i - 1][j - 1])
	print(min(dp[n - 1]))


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	k = []
	for i in range(n):
		k.append([0] * 501)
	for i in range(n - 1, -1, -1):
		if i == n - 1:
			for j in range(n, 501 - n + (i + 1)):
				k[i][j] = abs(l[i] - j)
			for j in range(501 - n + (i + 1) - 2, n - 1, -1):
				k[i][j] = min(k[i][j], k[i][j + 1])
		else:
			for j in range(i + 1, 501 - n + (i + 1)):
				k[i][j] = abs(l[i] - j) + k[i + 1][j + 1]
			for j in range(501 - n + (i + 1) - 2, i, -1):
				k[i][j] = min(k[i][j], k[i][j + 1])
	ans = 1000000000000000
	for i in range(1, 502 - n):
		ans = min(ans, k[0][i])
	print(ans)


from sys import *
input = stdin.readline

def minUnpleasant(a, index, time, dp, mx):
	if index == len(a):
		return 0
	if time >= mx:
		return float('inf')
	if dp[time][index] != None:
		return dp[time][index]
	mn = float('inf')
	for i in range(time, mx):
		mn = min(mn, abs(i - a[index]) + minUnpleasant(a, index + 1, i + 1, dp, mx))
	dp[time][index] = mn
	return mn
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	mx = max(a) + len(a) + 2
	mn = float('inf')
	dp = []
	for i in range(mx):
		d = [None for j in range(n)]
		dp.append(d)
	for i in range(1, mx):
		mn = min(mn, minUnpleasant(a, 0, i, dp, mx))
	stdout.write(str(mn) + '\n')


from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	n = int(stdin.readline())
	t = list(map(int, stdin.readline().split()))
	t.sort()
	dp = [[float('inf')] * (2 * n + 1) for i in range(n + 1)]
	dp[0][0] = 0
	for i in range(1, n + 1):
		nt = t[i - 1]
		for j in range(1, 2 * n + 1):
			for k in range(j):
				dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(nt - j))
	print(min(dp[n]))


n = int(input())

def badmood(L, j, i):
	return abs(L[j - 1] - i)

def main():
	l = int(input())
	L = sorted([int(x) for x in input().split(' ')])
	dp = []
	for i in range(2 * l + 1):
		dp.append([0] * (l + 1))
	for i in range(1, 2 * l + 1):
		for j in range(1, l + 1):
			if i == j:
				dp[i][j] = dp[i - 1][j - 1] + badmood(L, j, i)
			elif i > j:
				dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1] + badmood(L, j, i))
	return dp[2 * l][l]
for i in range(n):
	print(main())


import sys
import math
from collections import defaultdict, deque
sys.setrecursionlimit(10 ** 5)
input = sys.stdin.readline

def inar():
	return [int(el) for el in input().split()]

def solve(index, time, arr, n, dp):
	if index == n:
		return 0
	if dp[index][time] != -1:
		return dp[index][time]
	ans = 10 ** 18
	for i in range(time, max(time, arr[index]) + 1):
		ans = min(ans, abs(arr[index] - i) + solve(index + 1, i + 1, arr, n, dp))
	dp[index][time] = ans
	return ans

def main():
	t = int(input())
	for _ in range(t):
		dp = [[-1 for j in range(405)] for i in range(200)]
		n = int(input())
		arr = inar()
		arr.sort()
		print(solve(0, 1, arr, n, dp))
main()


for _ in range(int(input())):
	n = int(input())
	u = sorted(map(int, input().split()))
	d = [2 ** 31] * (2 * n + 1)
	for i in range(1, 2 * n + 1):
		d[i] = abs(u[0] - i)
	for i in range(1, n):
		cur = [2 ** 31] * (2 * n + 1)
		for j in range(1, 2 * n + 1):
			f = d[j]
			for k in range(j + 1, 2 * n + 1):
				cur[k] = min(cur[k], f + abs(u[i] - k))
		d = cur[:]
	print(min(d))


q = int(input())
for _ in range(q):
	n = int(input())
	l = [int(i) for i in input().split(' ')]
	l.sort()
	k = 400
	inf = k ** 2
	tb = [[-1 for j in range(n)] for i in range(k)]
	for i in range(n - 1, k):
		tb[i][n - 1] = abs(i + 1 - l[n - 1])
	for j in range(n - 1):
		tb[k - 1][j] = inf
	for j in range(1, n):
		for i in range(j):
			tb[i][j] = -2
	for i in range(k - 2, -1, -1):
		for j in range(n - 2, -1, -1):
			if tb[i][j] == -1:
				tb[i][j] = min(tb[i + 1][j], abs(i + 1 - l[j]) + tb[i + 1][j + 1])
	print(tb[0][0])


input = __import__('sys').stdin.readline
inf = float('inf')

def go(i, ct):
	if i == n:
		dp[i][ct] = 0
		return 0
	if dp[i][ct] != inf:
		return dp[i][ct]
	if ct >= s[i]:
		dp[i][ct] = go(i + 1, ct + 1) + abs(ct - s[i])
		return dp[i][ct]
	dp[i][ct] = min(go(i + 1, ct + 1) + abs(ct - s[i]), go(i, ct + 1))
	return dp[i][ct]
for _ in range(int(input())):
	n = int(input())
	s = sorted(map(int, input().split()))
	dp = [[inf] * (n * 2 + 3) for _ in range(n + 3)]
	print(go(0, 1))


def solve(n, t):
	t = sorted(t)
	m = max(t) + n
	dp = [[float('inf') for _ in range(m + 1)] for _ in range(n)]
	for j in range(1, m + 1):
		dp[0][j] = abs(j - t[0])
	for i in range(1, n):
		for j in range(i + 1, m + 1):
			dp[i][j] = min(dp[i - 1][:j]) + abs(t[i] - j)
	return min(dp[-1])
q = int(input())
for _ in range(q):
	n = int(input())
	t = list(map(int, input().split()))
	print(solve(n, t))


import sys
input = sys.stdin.readline

def rec(i, t):
	if i >= n:
		return 0
	if t > 2 * n + 10:
		return 10 ** 12
	if dp[i][t] != -1:
		return dp[i][t]
	dp[i][t] = min(abs(l[i] - t) + rec(i + 1, t + 1), rec(i, t + 1))
	return dp[i][t]
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	dp = []
	for i in range(n):
		o = []
		for j in range(2 * n + 11):
			o.append(-1)
		dp.append(o)
	print(rec(0, 1))


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import inf
T = int(input())
for t in range(T):
	N = int(input())
	arr = sorted(list(map(int, input().split())))
	lim = 2 * N + 2
	dp = [[inf] * lim for _ in range(N)]
	for j in range(1, lim):
		dp[0][j] = abs(arr[0] - j)
	for i in range(1, N):
		prefix = inf
		for j in range(1, lim):
			prefix = min(prefix, dp[i - 1][j - 1])
			dp[i][j] = min(dp[i][j], prefix + abs(arr[i] - j))
	print(min(dp[-1]))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	ml = [[float('inf')] * (2 * n) for i in range(n + 1)]
	for i in range(2 * n):
		ml[0][i] = 0
	ml[0][0] = 0
	for i in range(1, n + 1):
		for j in range(i, 2 * n):
			ml[i][j] = min(ml[i - 1][j - 1] + abs(arr[i - 1] - j), ml[i][j - 1])
	print(ml[-1][-1])


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import defaultdict

def gift():
	for _ in range(t):
		n = int(input())
		array = sorted(list(map(int, input().split())))
		dp = [[float('inf')] * (2 * n + 1) for i in range(n + 1)]
		dp[0][0] = 0
		for i in range(1, n + 1):
			nt = array[i - 1]
			for j in range(1, 2 * n + 1):
				for k in range(j):
					dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(nt - j))
		yield min(dp[n])
t = int(input())
ans = gift()
print(*ans, sep='\n')


from math import inf
dp = [[0 for i in range(402)] for j in range(202)]
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort()
	arr.insert(0, 0)
	for idx in range(1, n + 1):
		dp[idx][0] = inf
		for time in range(1, 2 * n + 1):
			dp[idx][time] = min(dp[idx - 1][time - 1] + abs(arr[idx] - time), dp[idx][time - 1])
	print(dp[n][2 * n])


import sys, os, io
I = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for tc in range(1, 1 + int(I())):
	n = int(I())
	t = list(map(int, I().split()))
	t.sort()
	N = n * 3
	p = [0] * N
	dp = dict()
	for i in range(N):
		dp[0, i] = int(1e+19)
		dp[i, 0] = 0
	for i in range(1, N):
		for j in range(1, n + 1):
			a = dp[i - 1, j]
			b = dp[i - 1, j - 1]
			c = abs(i - t[j - 1])
			dp[i, j] = min(a, b + c)
	print(min((dp[i, n] for i in range(N))))


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	(N,) = map(int, input().split())
	X = list(map(int, input().split()))
	dp = [[10 ** 18] * (2 * (N + 1)) for _ in range(N + 1)]
	for i in range(2 * (N + 1)):
		dp[0][i] = 0
	X.sort()
	for i in range(N):
		x = X[i]
		for t in range(2 * (N + 1)):
			for bt in range(t):
				dp[i + 1][t] = min(dp[i][bt] + abs(t - x), dp[i + 1][t])
	print(min(dp[-1]))


import sys
input = sys.stdin.readline

def prog():
	for _ in range(int(input())):
		n = int(input())
		t = list(map(int, input().split()))
		t.sort()
		ans = 10 ** 9
		dp = [[10 ** 9] * (2 * n + 1) for i in range(n + 1)]
		dp[0] = [0] * (2 * n + 1)
		for i in range(n):
			for time in range(1, 2 * n + 1):
				dp[i + 1][time] = min(dp[i + 1][time - 1], dp[i][time - 1] + abs(time - t[i]))
		print(dp[n][2 * n])
prog()


import sys, os
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
mod = 10 ** 9 + 7

def main():
	ans = ''
	MAX = 402
	for _ in range(int(input())):
		n = int(input())
		arr = read()
		arr.sort()
		dp = [[float('inf')] * MAX for i in range(n)]
		for i in range(1, MAX):
			dp[0][i] = min(dp[0][i - 1], abs(arr[0] - i))
		for i in range(1, n):
			for j in range(1, MAX):
				dp[i][j] = min(dp[i][j - 1], abs(arr[i] - j) + dp[i - 1][j - 1])
		ans += str(min(dp[n - 1])) + '\n'
	print(ans)
main()


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr = sorted(arr)
	dp = [[float('inf') for j in range(2 * n)] for i in range(n + 1)]
	for i in range(2 * n):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for j in range(1, 2 * n):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(j - arr[i - 1]), dp[i][j - 1])
	print(dp[n][-1])


test_cases = int(input())
for _ in range(test_cases):
	num_dishes = int(input())
	tempos = [int(x) for x in input().split()]
	tempos.sort()
	min_unp = [99999] * (num_dishes + 1)
	min_unp[0] = 0
	aux = 2 * num_dishes + 1
	for x in range(1, aux):
		for y in range(num_dishes, 0, -1):
			a = min_unp[y]
			b = min_unp[y - 1]
			c = abs(tempos[y - 1] - x)
			resp = min(a, b + c)
			min_unp[y] = resp
	print(min_unp[num_dishes])


def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		t = [int(word) for word in input().rstrip().split()]
		t.sort()
		dp = [[float('inf') for j in range(n + 1)] for i in range(0, t[-1] + n)]
		dp[0][0] = 0
		for i in range(1, t[-1] + n):
			dp[i][0] = 0
			for j in range(1, n + 1):
				dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1] + abs(i - t[j - 1]))
		print(dp[-1][n])
main()


import sys
input = sys.stdin.buffer.readline
q = int(input())
INF = 10 ** 9
for _ in range(q):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	max_t = 200
	dp = [[INF] * (n + 1) for i in range(2 * max_t + 1)]
	for pos in range(2 * max_t + 1):
		dp[pos][0] = 0
	for pos in range(2 * max_t):
		for cnt in range(n):
			val = abs(t[cnt] - (pos + 1))
			dp[pos + 1][cnt + 1] = min(dp[pos][cnt + 1], dp[pos][cnt] + val)
	ans = INF
	for pos in range(2 * max_t + 1):
		ans = min(dp[pos][n], INF)
	print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	high = a[-1] + n + 10
	INF = 1000000
	dp = [[INF for _ in range(high)] for _ in range(n + 1)]
	for i in range(0, n):
		for tt in range(i + 1, high):
			if i == 0:
				dp[i][tt] = abs(a[i] - tt)
			else:
				for xx in range(1, tt):
					dp[i][tt] = min(dp[i][tt], dp[i - 1][xx] + abs(a[i] - tt))
	print(min(dp[n - 1]))
for _ in range(int(input())):
	solve()


t = int(input())
for case in range(t):
	n = int(input())
	t = list(map(int, input().split()))
	t = sorted(t)
	dp = [[0 for i in range(2 * n + 1)] for j in range(n + 1)]
	for i in range(n):
		dp[i][2 * n] = 100000
	for j in reversed(range(2 * n)):
		for i in reversed(range(n)):
			opt1 = dp[i][j + 1]
			opt2 = dp[i + 1][j + 1] + abs(j - t[i])
			dp[i][j] = min(opt1, opt2)
	print(dp[0][1])


for _ in range(int(input())):
	num_dishes = int(input())
	dishes = list(map(int, input().split()))
	best_result = [[0] * (num_dishes + 1) for i in range(2 * num_dishes + 1)]
	dishes.sort()
	for i in range(num_dishes):
		best_result[2 * num_dishes][i] = 1000000
	for t in range(2 * num_dishes - 1, 0, -1):
		for d in range(num_dishes - 1, -1, -1):
			best_result[t][d] = min(best_result[t + 1][d], abs(dishes[d] - t) + best_result[t + 1][d + 1])
	print(best_result[1][0])


import sys
max_int = 1000000001
min_int = -max_int
q = int(input())
for _q in range(q):
	n = int(sys.stdin.readline())
	t = list(map(int, sys.stdin.readline().split()))
	t.sort()
	DP = [[max_int] * (n * 2 + 10) for _ in range(n)]
	for i in range(n):
		for time in range(1, n * 2 + 10):
			if i:
				DP[i][time] = min(DP[i - 1][time - 1] + abs(time - t[i]), DP[i][time], DP[i][time - 1])
			else:
				DP[0][time] = min(abs(time - t[0]), DP[i][time - 1])
	print(DP[-1][-1])


for _ in range(int(input())):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	a.sort()
	inf = 10 ** 12
	dp = [[inf for i in range(2 * n + 1)] for j in range(n + 1)]
	for i in range(2 * n + 1):
		dp[0][i] = 0
	for i in range(n + 1):
		dp[i][0] = 0
	dp[0][0] = 0
	for i in range(1, n + 1):
		dp[i][i] = dp[i - 1][i - 1] + abs(i - a[i])
	for i in range(1, n + 1):
		for j in range(i + 1, 2 * n + 1):
			dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] + abs(a[i] - j))
	print(dp[n][2 * n])


t = int(input())
for _ in range(t):
	input()
	a = sorted(list(map(int, input().split(' '))))
	s = set()
	res = 0
	b = []
	for i in range(0, len(a)):
		v = i + 1
		res += abs(a[i] - (i + 1))
		b.append(i + 1)
	while True:
		prev = res
		for i in range(len(a) - 1, -1, -1):
			for j in range(i + 1, len(a) + 1):
				if j - 1 == len(a) - 1 or b[j - 1] + 1 != b[j]:
					s1 = 0
					s2 = 0
					for k in range(i, j):
						s1 += abs(a[k] - b[k])
						s2 += abs(a[k] - (b[k] + 1))
					if s1 > s2:
						res -= s1 - s2
						for k in range(i, j):
							b[k] += 1
		if res == prev:
			break
	print(res)


test_cases = int(input())
for test_case in range(test_cases):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	time = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300]
	matrix = [[abs(time[0] - t[0])]]
	for i in range(1, n):
		matrix[0].append(10000000)
	for i in range(1, len(time)):
		matrix.append([min(abs(t[0] - time[i]), matrix[i - 1][0])])
	for i in range(1, len(time)):
		for j in range(1, n):
			matrix[i].append(min(abs(t[j] - time[i]) + matrix[i - 1][j - 1], matrix[i - 1][j]))
	print(matrix[-1][-1])


def find_min_unpleasure(minute, dish_index):
	configuration = str(minute) + str(dish_index)
	if configuration in situations:
		return situations[configuration]
	if dish_index == dish_amount - 1:
		if minute > dish_timings[dish_index]:
			log_encounter_situation(configuration, minute - dish_timings[dish_index])
			return minute - dish_timings[dish_index]
		log_encounter_situation(configuration, 0)
		return 0
	current_unpleasure = abs(dish_timings[dish_index] - minute)
	if minute >= dish_timings[dish_index]:
		time = current_unpleasure + find_min_unpleasure(minute + 1, dish_index + 1)
		log_encounter_situation(configuration, time)
		return time
	not_take_now = find_min_unpleasure(minute + 1, dish_index)
	take_now = current_unpleasure + find_min_unpleasure(minute + 1, dish_index + 1)
	optimal_at_current = min(not_take_now, take_now)
	log_encounter_situation(configuration, optimal_at_current)
	return optimal_at_current

def log_encounter_situation(configuration, optimal_at_current):
	if configuration in situations:
		if situations[configuration] > optimal_at_current:
			situations[configuration] = optimal_at_current
	else:
		situations[configuration] = optimal_at_current
test_amount = int(input())
for i in range(test_amount):
	situations = {}
	dish_amount = int(input())
	dish_timings = list(map(int, input().split()))
	dish_timings = sorted(dish_timings)
	find_min_unpleasure(1, 0)
	print(situations['10'])


import sys
import math
input = sys.stdin.readline

def pi():
	return int(input())

def pl():
	return int(input(), 16)

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

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

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

def main():
	C()
nMap = [0 for i in range(200005)]
indexMap = [[] for i in range(200005)]
mod = 998244353

def A():
	t = pi()
	while t:
		t -= 1
		(n, a) = (pi(), ti())
		right = [0 for i in range(n)]
		right[n - 1] = a[n - 1]
		for i in range(n - 2, -1, -1):
			right[i] = min(a[i], right[i + 1])
		mn = a[0]
		f = 0
		res = 1
		ans = [0 for i in range(n)]
		for i in range(0, n):
			mn = min(mn, a[i])
			if a[i] - mn == 0:
				f = 1
				ans[i] = 1
				a[i] = 0
				continue
			if a[i] - mn > 0:
				a[i] -= mn
				if f:
					break
				elif right[i] < a[i] - mn:
					res = 0
					break
		if res == 0:
			print('NO')
			continue
		index = 0
		for i in range(n):
			if ans[i] != 0:
				break
			index = i
		res = 1
		for i in range(index + 2, n):
			if a[i] < a[i - 1]:
				res = 0
				break
		if res:
			print('YES')
		else:
			print('NO')

def solve(n, t, ct, index, mx, dp):
	if index >= n:
		return 0
	if ct > mx:
		return 9999999999999
	if dp[index][ct] != -1:
		return dp[index][ct]
	mn = 9999999999999
	for i in range(ct, mx + 1):
		mn = min(mn, abs(i - t[index]) + solve(n, t, i + 1, index + 1, mx, dp))
	dp[index][ct] = mn
	return mn

def C():
	q = pi()
	while q:
		q -= 1
		(n, t) = (pi(), ti())
		dp = [[-1 for j in range(2 * n + 1)] for i in range(n)]
		print(solve(n, sorted(t), 1, 0, 2 * n, dp))
main()


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

def go(a, pos, val, n, memo):
	if pos == n:
		return 0
	if val > 2 * n:
		return 10 ** 7
	if memo[pos][val] != -1:
		return memo[pos][val]
	ans = sys.maxsize
	ans = min(ans, abs(a[pos] - val) + go(a, pos + 1, val + 1, n, memo))
	ans = min(ans, go(a, pos, val + 1, n, memo))
	memo[pos][val] = ans
	return memo[pos][val]

def solve():
	n = int(input())
	memo = [[-1 for i in range(2 * n + 3)] for j in range(n + 5)]
	a = list(map(int, input().split()))
	a.sort()
	print(go(a, 0, 1, n, memo))
for _ in range(int(input())):
	solve()


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
t = int(input())
for _ in range(t):
	n = int(input())
	ml = 400
	arr = list(map(int, input().split()))
	arr.sort()
	dp = [abs(arr[0] - i) for i in range(ml)]
	dp[0] = float('inf')
	for i in range(1, n):
		for j in range(i + 1, ml):
			dp[j] = min(dp[j], dp[j - 1])
		ndp = dp[:]
		for j in range(i + 1, ml):
			ndp[j] = dp[j - 1] + abs(arr[i] - j)
		dp = ndp[:]
	ans = float('inf')
	for j in range(n, ml):
		ans = min(ans, dp[j])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	A = [int(x) for x in input().split()]
	A.sort()
	min_array = [100000] * (n + 1)
	min_array[0] = 0
	for i in range(1, 2 * n):
		for j in range(n, 0, -1):
			min_array[j] = min(min_array[j], min_array[j - 1] + abs(A[j - 1] - i))
	print(min_array[n])


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	dp = [[0 for j in range(2 * n + 1)] for i in range(n + 1)]
	for i in range(1, n + 1):
		for j in range(1, 2 * n + 1):
			dp[i][j] = dp[i - 1][j - 1] + abs(a[i - 1] - j)
			if j > i and dp[i][j] > dp[i][j - 1]:
				dp[i][j] = dp[i][j - 1]
	print(dp[n][2 * n])


import array

def Abs(x):
	if x < 0:
		return -x
	return x

def solve():
	n = int(input())
	a = array.array('i', map(int, input().split()))
	b = array.array('i', [0 for i in range(3 * n)])
	c = array.array('i', [1 << 30 for i in range(3 * n)])
	c[0] = 0
	for i in range(n):
		b[a[i] + n] += 1
	for i in range(1, 3 * n):
		b[i] += b[i - 1]
	for i in range(n + 1, 3 * n):
		for j in range(n, 0, -1):
			c[j] = min(c[j], c[j - 1])
		for j in range(n + 1):
			c[j] += Abs(j - b[i])
	print(c[n])
T = int(input())
for Tid in range(T):
	solve()


T = int(input())
for _ in range(T):
	N = int(input())
	T = sorted(map(int, input().split()))
	Ans = [False] * (3 * N)
	for (idx_T, t) in enumerate(T):
		mi = 1 << 60
		ami = -100
		for i in range(1, 3 * N):
			if Ans[i]:
				continue
			Ans[i] = True
			an = 0
			j = 1
			for t2 in T[:idx_T + 1]:
				while not Ans[j]:
					j += 1
				an += abs(t2 - j)
				j += 1
			if mi > an:
				mi = an
				ami = i
			Ans[i] = False
		Ans[ami] = True
	print(mi)


def calc(pos, time):
	if pos == n - 1:
		return abs(a[n - 1] - time)
	if time > 405:
		return 1 << 30
	if dp[pos][time] != -1:
		return dp[pos][time]
	dp[pos][time] = 1 << 30
	dp[pos][time] = min(dp[pos][time], calc(pos, time + 1), calc(pos + 1, time + 1) + abs(a[pos] - time))
	return dp[pos][time]
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[-1 for _ in range(410)] for _ in range(410)]
	print(calc(0, 1))


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf
from itertools import permutations
from copy import deepcopy
from heapq import *
from sys import setrecursionlimit

def main():
	for _ in range(int(input())):
		n = int(input())
		a = sorted(map(int, input().split()))
		z = a[-1] + n + 1
		dp = [[inf for j in range(z)] for j in range(n + 1)]
		for i in range(z):
			dp[0][i] = 0
		for i in range(1, n + 1):
			for j in range(i, z):
				dp[i][j] = min(dp[i - 1][j - 1] + abs(j - a[i - 1]), dp[i][j - 1])
		print(min(dp[-1]))
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 time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

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

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * (2 * 10 ** 5 + 5)
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(2 * 10 ** 5 + 5):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return

def readTree(n, e):
	adj = [set() for i in range(n + 1)]
	for i in range(e):
		(u1, u2) = IP()
		adj[u1].add(u2)
	return adj
mod = 10 ** 9 + 7

def solve():
	n = II()
	t = L()
	t.sort()
	dp = [[1000000000.0 for j in range(1001)] for i in range(n + 1)]
	for i in range(1001):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for j in range(1, 1001):
			dp[i][j] = min(dp[i][j], dp[i][j - 1])
			if dp[i - 1][j - 1] != 1000000000.0:
				dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + abs(j - t[i - 1]))
	print(dp[n][1000])
	return
t = II()
for i in range(t):
	solve()


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[0] * 401 for _ in range(n)]
	dp[0][0] = a[0]
	for i in range(1, 401):
		dp[0][i] = min(dp[0][i - 1], abs(i - a[0]))
	for i in range(1, n):
		for j in range(i + 1, 401):
			if i + 1 == j:
				dp[i][j] = dp[i - 1][j - 1] + abs(j - a[i])
				continue
			dp[i][j] = min(dp[i - 1][j - 1] + abs(j - a[i]), dp[i][j - 1])
	print(dp[-1][-1])


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

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

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

def invr():
	return map(int, input().split())
n = inp()
for i in range(n):
	y = inp()
	l = inlt()
	l.sort()
	minute = 0
	dp = [0] * 402
	first = l[0]
	for j in range(y - 1):
		new_dp = [200000] * 402
		for k in range(402):
			if k + 1 <= l[j]:
				for p in range(k + 1, l[j] + 1):
					if dp[k] + abs(l[j] - p) < new_dp[p]:
						new_dp[p] = dp[k] + abs(l[j] - p)
			elif dp[k] + abs(l[j] - k - 1) < new_dp[p]:
				new_dp[k + 1] = dp[k] + abs(l[j] - k - 1)
		dp = new_dp.copy()
	new_dp = [200000] * 402
	for j in range(402):
		if j < l[-1]:
			if dp[j] < new_dp[l[-1]]:
				new_dp[l[-1]] = dp[j]
		elif dp[j] + abs(l[-1] - j - 1) < new_dp[l[-1]]:
			new_dp[l[-1]] = dp[j] + abs(l[-1] - j - 1)
	new_dp.sort()
	print(min(new_dp))


import sys
from functools import lru_cache
max_int = 1000000001
min_int = -max_int

@lru_cache(None)
def rec(time, i):
	if i == len(t):
		return 0
	if time == len(t) * 2 + 10:
		return 10 ** 5
	return min(rec(time + 1, i + 1) + abs(t[i] - time), rec(time + 1, i))
q = int(input())
for _q in range(q):
	n = int(sys.stdin.readline())
	t = list(map(int, sys.stdin.readline().split()))
	t.sort()
	rec.cache_clear()
	print(rec(1, 0))


from sys import stdin
input = stdin.readline

def solve():
	INF = 10 ** 5
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	m = 350
	dp = [[INF] * m for _ in range(n)]
	dp[0] = [INF] + [abs(i - a[0]) for i in range(1, m)]
	if n == 1:
		print(0)
		return
	for cur in range(1, n):
		mn = INF
		for last in range(1, m):
			dp[cur][last] = mn + abs(last - a[cur])
			mn = min(mn, dp[cur - 1][last])
	print(min(dp[-1]))
t = int(input())
for _ in range(t):
	solve()


import sys
input = sys.stdin.readline
for test in range(int(input())):
	n = int(input())
	t = list(map(int, input().split(' ')))
	t.sort()
	o = []
	u = []
	for i in range(n):
		if not o or t[i] > o[-1]:
			o.append(t[i])
			u.append(0)
		else:
			o.append(o[-1] + 1)
			u.append(o[-2] - t[i] + 1)
			j = len(o) - 3
			spoj = 2
			while j > -1 and o[j] == o[j + 1] - 1:
				spoj += 1
				j -= 1
			alt1 = sum([abs(k) for k in u[j + 1:len(o)]])
			ualt = [abs(k - 1) for k in u[j + 1:len(o)]]
			alt2 = sum(ualt)
			if alt2 < alt1 and o[j + 1] > 1:
				for h in range(j + 1, len(o)):
					o[h] -= 1
					u[h] -= 1
	print(sum([abs(k) for k in u]))


import math
IP = lambda : list(map(int, input().split()))
for _ in range(int(input())):
	n = int(input())
	a = sorted(IP())
	dp = [[float('inf')] * 401 for _ in range(n + 1)]
	for i in range(n):
		for j in range(1, 401):
			if i == 0:
				dp[i][j] = abs(a[i] - j)
			else:
				dp[i][j] = min(dp[i - 1][:j]) + abs(a[i] - j)
	print(min(dp[n - 1]))


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 *
from collections import deque
from operator import itemgetter, attrgetter
from decimal import *
import bisect
import math
import heapq as hq
MOD = 10 ** 9 + 7

def is_prime(n):
	if n == 2 or n == 3:
		return True
	if n < 2 or n % 2 == 0:
		return False
	if n < 9:
		return True
	if n % 3 == 0:
		return False
	r = int(n ** 0.5)
	f = 5
	while f <= r:
		if n % f == 0:
			return False
		if n % (f + 2) == 0:
			return False
		f += 6
	return True

def pow(a, b, m):
	ans = 1
	while b:
		if b & 1:
			ans = ans * a % m
		b //= 2
		a = a * a % m
	return ans

def ispalindrome(s):
	if s[:] == s[::-1]:
		return 1
	return 0
dp = []
limit = []
v = []

def dpdfs(u, t=-1):
	dp[0][u] = 0
	dp[1][u] = 0
	for i in v[u]:
		if i == t:
			continue
		if dp[1][i] == -1:
			dpdfs(i, u)
		dp[0][u] += max(abs(limit[0][u] - limit[1][i]) + dp[1][i], abs(limit[0][u] - limit[0][i]) + dp[0][i])
		dp[1][u] += max(abs(limit[1][u] - limit[1][i]) + dp[1][i], abs(limit[1][u] - limit[0][i]) + dp[0][i])
vis = []
f = 0

def dfs(i):
	vis[i] = 1
	act[i] = 1
	for j in v[i]:
		if act[j]:
			f = 1
			return -1
		if vis[j] == 0:
			if dfs(j) == -1:
				return -1
	act[i] = 0
	ans.append(i)
	return 0
from queue import PriorityQueue

def z_algorithm(s):
	res = [0] * len(s)
	res[0] = len(s)
	(i, j) = (1, 0)
	while i < len(s):
		while i + j < len(s) and s[j] == s[i + j]:
			j += 1
		res[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < len(s) and k + res[k] < j:
			res[i + k] = res[k]
			k += 1
		(i, j) = (i + k, j - k)
	return res

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

def lcm(a, b):
	return a / gcd(a, b) * b
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	for i in range(n):
		l[i] -= 1
	dp = [[math.inf for i in range(2 * n)] for j in range(n + 1)]
	dp[0][0] = 0
	for i in range(n + 1):
		for j in range(2 * n - 1):
			if dp[i][j] < math.inf:
				if i < n:
					dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(l[i] - j))
				dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	print(dp[n][2 * n - 1])


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

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

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			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')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7
from bisect import bisect_left

def solve():
	N = getInt()
	T = getInts()
	T.sort()
	dp = [[10 ** 9 for j in range(2 * N + 1)] for i in range(N + 1)]
	dp[0][1] = 0
	for i in range(N + 1):
		for j in range(1, 2 * N):
			if dp[i][j] < 10 ** 9:
				if i < N:
					dp[i + 1][j + 1] = min(dp[i][j] + abs(T[i] - j), dp[i + 1][j + 1])
				dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	return dp[N][2 * N]
for _ in range(getInt()):
	print(solve())


def time(n, t):
	if n == N:
		return 0
	if n < N and t == 2 * N:
		return 10 ** 7
	elif dp[n][t] != -1:
		return dp[n][t]
	else:
		dp[n][t] = min(time(n, t + 1), abs(A[n] - t) + time(n + 1, t + 1))
		return min(time(n, t + 1), abs(A[n] - t) + time(n + 1, t + 1))
for _ in range(int(input())):
	N = int(input())
	A = [int(i) for i in input().split(' ')]
	A.sort()
	dp = []
	for i in range(N + 1):
		dp += [[-1] * (2 * N + 1)]
	print(time(0, 1))


def ans(n, c):
	if dp[n][c] != -1:
		return dp[n][c]
	if n == act:
		return 0
	if c == 350:
		return float('inf')
	else:
		dp[n][c] = min(abs(l[n] - c) + ans(n + 1, c + 1), ans(n, c + 1))
		return min(abs(l[n] - c) + ans(n + 1, c + 1), ans(n, c + 1))
for _ in range(int(input())):
	act = int(input())
	dp = [[-1 for i in range(351)] for j in range(act + 1)]
	l = list(map(int, input().split()))
	l.sort()
	x = ans(0, 1)
	print(x)


def read_int():
	return int(input())

def read_ints():
	return map(int, input().split(' '))
inf = int(1000000000.0)
t = read_int()
for case_num in range(t):
	n = read_int()
	a = list(read_ints())
	a.sort()
	dp = [0 for _ in range(n * 2 + 1)]
	for t in a:
		ndp = [inf for _ in range(n * 2 + 1)]
		lo = inf
		for i in range(n * 2):
			lo = min(lo, dp[i])
			ndp[i + 1] = min(ndp[i + 1], lo + abs(i + 1 - t))
		dp = ndp
	print(min(dp))


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7

def dp(ind, val):
	if ind == n:
		return 0
	if v[ind][val] != -1:
		return v[ind][val]
	if a[ind] >= val:
		v[ind][val] = min([a[ind] - i + dp(ind + 1, i + 1) for i in range(val, a[ind] + 1)])
		return v[ind][val]
	else:
		v[ind][val] = val - a[ind] + dp(ind + 1, val + 1)
		return v[ind][val]
for _ in range(I()):
	n = I()
	a = sorted(R())
	v = [[-1] * (500 + 1) for i in range(500 + 1)]
	print(dp(0, 1))


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	t = sorted(list(map(int, input().split())))
	inf = 10 ** 5
	dp = [[inf for j in range(3 * n // 2 + 1)] for i in range(n + 1)]
	dp[0][0] = 0
	for i in range(n + 1):
		for j in range(3 * n // 2):
			if i < n:
				dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(t[i] - (j + 1)))
			dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	print(dp[n][3 * n // 2])


import typing
import sys
import math
import collections
import bisect
import itertools
import heapq
import decimal
INF = 10 ** 20
MOD = 10 ** 9 + 7

def ni():
	return int(sys.stdin.buffer.readline())

def na():
	return list(map(int, sys.stdin.buffer.readline().split()))

def na1():
	return list(map(lambda x: int(x) - 1, sys.stdin.buffer.readline().split()))

def main():
	t = ni()
	for _ in range(t):
		n = ni()
		a = na()
		a.sort()
		dp = [[INF for _ in range(n + 1)] for _ in range(2 * n + 1)]
		for i in range(2 * n + 1):
			dp[i][0] = 0
		for i in range(1, 2 * n + 1):
			for j in range(n + 1):
				dp[i][j] = min(dp[i][j], dp[i - 1][j], dp[i - 1][j - 1] + abs(i - a[j - 1]))
		print(dp[2 * n][n])
main()


import sys
from math import ceil, factorial, gcd
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify
MOD = 10 ** 9 + 7
INF = float('inf')
rl = lambda : list(map(int, sys.stdin.readline().split()))
for _ in range(int(input())):
	n = int(input())
	T = sorted(rl())
	dp = [[-1 for j in range(2 * n)] for i in range(n + 1)]
	for i in range(2 * n):
		dp[0][i] = 0
	for i in range(1, n + 1):
		dp[i][0] = INF
	for i in range(1, n + 1):
		for j in range(1, 2 * n):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(j - T[i - 1]), dp[i][j - 1])
	print(dp[-1][-1])


mx = 100000000000
T = int(input())
for _ in range(0, T):
	n = int(input())
	s = [int(x) for x in input().split()]
	s.sort()
	ans = mx
	dp = []
	for i in range(0, 401):
		h = []
		for j in range(n):
			h.append(0)
		dp.append(h)
	mn = [mx] * n
	for i in range(400, 0, -1):
		for j in range(n - 1, -1, -1):
			rem = n - j - 1
			if rem > 400 - i:
				dp[i][j] = mx
			elif j == n - 1:
				dp[i][j] = abs(s[j] - i)
			else:
				dp[i][j] = min(mx, abs(s[j] - i) + mn[j + 1])
		for j in range(0, n):
			mn[j] = min(mn[j], dp[i][j])
	for i in range(1, 401):
		ans = min(ans, dp[i][0])
	print(ans)


def process_test_case(i_t):
	n = int(input())
	t_vec = list(map(int, input().split()))
	t_vec.sort()
	dp = [[0] * (n + 1) for _ in range(2 * n + 1)]
	for i in range(1, 2 * n + 1):
		for j in range(1, min(i + 1, n + 1)):
			if i == j:
				dp[i][j] = dp[i - 1][j - 1] + abs(i - t_vec[j - 1])
			else:
				dp[i][j] = min(dp[i - 1][j - 1] + abs(i - t_vec[j - 1]), dp[i - 1][j])
	answer = min([sub_dp[n] for sub_dp in dp[n:]])
	print(answer)
	return None
n_tests = int(input())
for i_test in range(1, n_tests + 1):
	process_test_case(i_test)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from typing import List
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
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')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

@lru_cache(None)
def fact(x, mod=0):
	if x < 2:
		return 1
	if not mod:
		return fact(x - 1) * x
	return fact(x - 1, mod) * x % mod

@lru_cache(None)
def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	ans = 1
	for k in range(i - j + 1, i + 1):
		ans = ans * k % mod
	return ans

@lru_cache(None)
def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j) * inverse(fact(j), mod) % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

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

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class smt:

	def __init__(self, l, r, arr):
		self.l = l
		self.r = r
		self.value = (1 << 31) - 1 if l < r else arr[l]
		mid = (l + r) // 2
		if l < r:
			self.left = smt(l, mid, arr)
			self.right = smt(mid + 1, r, arr)
			self.value &= self.left.value & self.right.value

	def setvalue(self, x, val):
		if self.l == self.r:
			self.value = val
			return
		mid = (self.l + self.r) // 2
		if x <= mid:
			self.left.setvalue(x, val)
		else:
			self.right.setvalue(x, val)
		self.value = self.left.value & self.right.value

	def ask(self, l, r):
		if l <= self.l and r >= self.r:
			return self.value
		val = (1 << 31) - 1
		mid = (self.l + self.r) // 2
		if l <= mid:
			val &= self.left.ask(l, r)
		if r > mid:
			val &= self.right.ask(l, r)
		return val

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

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

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

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

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d
q = N()
for i in range(q):
	n = N()
	t = RLL()
	t.sort()
	ma = n + n // 2
	dp = [[inf] * (n + 1) for i in range(ma + 1)]
	dp[0][0] = 0
	for i in range(1, ma + 1):
		dp[i][0] = 0
		for j in range(1, n + 1):
			dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + abs(i - t[j - 1]), dp[i - 1][j])
	print(dp[ma][n])


import sys
import math
input = sys.stdin.readline

def get_int():
	return int(input().strip())

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

def get_char_list():
	return list(input().strip())
cases = get_int()
for _ in range(cases):
	n = get_int()
	ints = get_int_list()
	ints.sort()
	end = ints[-1] + n
	f = []
	g = []
	for i in range(n):
		f.append([n * n] * (end + 1))
		g.append([n * n] * (end + 1))
	for i in range(n):
		for j in range(1, end + 1):
			if i > 0:
				f[i][j] = min(f[i][j], g[i - 1][j - 1] + abs(j - ints[i]))
			elif i == 0:
				f[i][j] = abs(j - ints[i])
			for k in range(j + 1):
				g[i][j] = min(g[i][j], f[i][k])
	print(min(g[n - 1]))


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

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))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

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

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

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

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

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

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

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

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(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
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

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

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

def solve():
	n = N()
	ar = lis()
	ar.sort()
	inf = float('inf')
	dp = [[inf] * (3 * n) for _ in range(n + 1)]
	for i in range(3 * n):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for t in range(1, 3 * n):
			for t2 in range(0, t):
				dp[i][t] = min(dp[i][t], dp[i - 1][t2] + abs(ar[i - 1] - t))
	print(min(dp[n]))
testcase(int(inp()))


def solve(n, d):
	big = float('inf')
	small = float('-inf')
	dp = []
	for _ in range(n):
		dp.append([0 for i in range(2 * n)])
	d.sort()
	for i in range(n):
		for j in range(i + 1, 2 * n):
			curr = abs(d[i] - j)
			if i > 0:
				curr += dp[i - 1][j - 1]
			if j > i + 1:
				curr = min(curr, dp[i][j - 1])
			dp[i][j] = curr
	return dp[-1][-1]

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		d = input()
		d = [int(i) for i in d.split()]
		ans = solve(n, d)
		print(ans)
main()


T = int(input())
for case in range(T):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	for k in range(n):
		t[k] -= k + 1
	for k in range(n):
		while t[k] > 0:
			sum_orig = 0
			sum_after = 0
			brkcnt = False
			for l in range(k, n):
				sum_orig += abs(t[l])
				sum_after += abs(t[l] - 1)
				if sum_orig < sum_after:
					brkcnt = True
					break
			if brkcnt == True:
				break
			if sum_orig > sum_after:
				for l in range(k, n):
					t[l] -= 1
			else:
				break
	print(sum(map(abs, t)))


for tt in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	dp = [[[float('inf')] * 2 for i in range(n + 1)] for j in range(350)]
	dp[0][0][0] = 0
	for i in range(349):
		for j in range(n + 1):
			for k in range(2):
				if j + 1 <= n:
					dp[i + 1][j + 1][1] = min(dp[i + 1][j + 1][k], dp[i][j][k] + abs(a[j] - i - 1))
				dp[i + 1][j][0] = min(dp[i + 1][j][0], dp[i][j][k])
	print(min(dp[-1][n]))


def fval(n, A):
	A.sort()
	dp = [[float('inf')] * (2 * n + 1) for _ in range(n + 1)]
	for i in range(2 * n + 1):
		dp[0][i] = 0
	for i in range(n):
		for j in range(2 * n):
			dp[i + 1][j + 1] = min(dp[i][j] + abs(A[i] - (j + 1)), dp[i + 1][j])
	return dp[-1][-1]
T = int(input())
for _ in range(T):
	n = int(input())
	C = list(map(int, input().split()))
	print(fval(n, C))


import sys, os
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict
__docformat__ = 'markdown'
import sys
import copy
from typing import Union, NewType, Sequence, Tuple, Optional, Callable
__all__ = ['Munkres', 'make_cost_matrix', 'DISALLOWED']
AnyNum = NewType('AnyNum', Union[int, float])
Matrix = NewType('Matrix', Sequence[Sequence[AnyNum]])
__version__ = '1.1.4'
__author__ = 'Brian Clapper, bmc@clapper.org'
__url__ = 'https://software.clapper.org/munkres/'
__copyright__ = '(c) 2008-2020 Brian M. Clapper'
__license__ = 'Apache Software License'

class DISALLOWED_OBJ(object):
	pass
DISALLOWED = DISALLOWED_OBJ()
DISALLOWED_PRINTVAL = 'D'

class UnsolvableMatrix(Exception):
	pass

class Munkres:

	def __init__(self):
		self.C = None
		self.row_covered = []
		self.col_covered = []
		self.n = 0
		self.Z0_r = 0
		self.Z0_c = 0
		self.marked = None
		self.path = None

	def pad_matrix(self, matrix: Matrix, pad_value: int=0) -> Matrix:
		max_columns = 0
		total_rows = len(matrix)
		for row in matrix:
			max_columns = max(max_columns, len(row))
		total_rows = max(max_columns, total_rows)
		new_matrix = []
		for row in matrix:
			row_len = len(row)
			new_row = row[:]
			if total_rows > row_len:
				new_row += [pad_value] * (total_rows - row_len)
			new_matrix += [new_row]
		while len(new_matrix) < total_rows:
			new_matrix += [[pad_value] * total_rows]
		return new_matrix

	def compute(self, cost_matrix: Matrix) -> Sequence[Tuple[int, int]]:
		self.C = self.pad_matrix(cost_matrix)
		self.n = len(self.C)
		self.original_length = len(cost_matrix)
		self.original_width = len(cost_matrix[0])
		self.row_covered = [False for i in range(self.n)]
		self.col_covered = [False for i in range(self.n)]
		self.Z0_r = 0
		self.Z0_c = 0
		self.path = self.__make_matrix(self.n * 2, 0)
		self.marked = self.__make_matrix(self.n, 0)
		done = False
		step = 1
		steps = {1: self.__step1, 2: self.__step2, 3: self.__step3, 4: self.__step4, 5: self.__step5, 6: self.__step6}
		while not done:
			try:
				func = steps[step]
				step = func()
			except KeyError:
				done = True
		results = []
		for i in range(self.original_length):
			for j in range(self.original_width):
				if self.marked[i][j] == 1:
					results += [(i, j)]
		return results

	def __copy_matrix(self, matrix: Matrix) -> Matrix:
		return copy.deepcopy(matrix)

	def __make_matrix(self, n: int, val: AnyNum) -> Matrix:
		matrix = []
		for i in range(n):
			matrix += [[val for j in range(n)]]
		return matrix

	def __step1(self) -> int:
		C = self.C
		n = self.n
		for i in range(n):
			vals = [x for x in self.C[i] if x is not DISALLOWED]
			if len(vals) == 0:
				raise UnsolvableMatrix('Row {0} is entirely DISALLOWED.'.format(i))
			minval = min(vals)
			for j in range(n):
				if self.C[i][j] is not DISALLOWED:
					self.C[i][j] -= minval
		return 2

	def __step2(self) -> int:
		n = self.n
		for i in range(n):
			for j in range(n):
				if self.C[i][j] == 0 and (not self.col_covered[j]) and (not self.row_covered[i]):
					self.marked[i][j] = 1
					self.col_covered[j] = True
					self.row_covered[i] = True
					break
		self.__clear_covers()
		return 3

	def __step3(self) -> int:
		n = self.n
		count = 0
		for i in range(n):
			for j in range(n):
				if self.marked[i][j] == 1 and (not self.col_covered[j]):
					self.col_covered[j] = True
					count += 1
		if count >= n:
			step = 7
		else:
			step = 4
		return step

	def __step4(self) -> int:
		step = 0
		done = False
		row = 0
		col = 0
		star_col = -1
		while not done:
			(row, col) = self.__find_a_zero(row, col)
			if row < 0:
				done = True
				step = 6
			else:
				self.marked[row][col] = 2
				star_col = self.__find_star_in_row(row)
				if star_col >= 0:
					col = star_col
					self.row_covered[row] = True
					self.col_covered[col] = False
				else:
					done = True
					self.Z0_r = row
					self.Z0_c = col
					step = 5
		return step

	def __step5(self) -> int:
		count = 0
		path = self.path
		path[count][0] = self.Z0_r
		path[count][1] = self.Z0_c
		done = False
		while not done:
			row = self.__find_star_in_col(path[count][1])
			if row >= 0:
				count += 1
				path[count][0] = row
				path[count][1] = path[count - 1][1]
			else:
				done = True
			if not done:
				col = self.__find_prime_in_row(path[count][0])
				count += 1
				path[count][0] = path[count - 1][0]
				path[count][1] = col
		self.__convert_path(path, count)
		self.__clear_covers()
		self.__erase_primes()
		return 3

	def __step6(self) -> int:
		minval = self.__find_smallest()
		events = 0
		for i in range(self.n):
			for j in range(self.n):
				if self.C[i][j] is DISALLOWED:
					continue
				if self.row_covered[i]:
					self.C[i][j] += minval
					events += 1
				if not self.col_covered[j]:
					self.C[i][j] -= minval
					events += 1
				if self.row_covered[i] and (not self.col_covered[j]):
					events -= 2
		if events == 0:
			raise UnsolvableMatrix('Matrix cannot be solved!')
		return 4

	def __find_smallest(self) -> AnyNum:
		minval = sys.maxsize
		for i in range(self.n):
			for j in range(self.n):
				if not self.row_covered[i] and (not self.col_covered[j]):
					if self.C[i][j] is not DISALLOWED and minval > self.C[i][j]:
						minval = self.C[i][j]
		return minval

	def __find_a_zero(self, i0: int=0, j0: int=0) -> Tuple[int, int]:
		row = -1
		col = -1
		i = i0
		n = self.n
		done = False
		while not done:
			j = j0
			while True:
				if self.C[i][j] == 0 and (not self.row_covered[i]) and (not self.col_covered[j]):
					row = i
					col = j
					done = True
				j = (j + 1) % n
				if j == j0:
					break
			i = (i + 1) % n
			if i == i0:
				done = True
		return (row, col)

	def __find_star_in_row(self, row: Sequence[AnyNum]) -> int:
		col = -1
		for j in range(self.n):
			if self.marked[row][j] == 1:
				col = j
				break
		return col

	def __find_star_in_col(self, col: Sequence[AnyNum]) -> int:
		row = -1
		for i in range(self.n):
			if self.marked[i][col] == 1:
				row = i
				break
		return row

	def __find_prime_in_row(self, row) -> int:
		col = -1
		for j in range(self.n):
			if self.marked[row][j] == 2:
				col = j
				break
		return col

	def __convert_path(self, path: Sequence[Sequence[int]], count: int) -> None:
		for i in range(count + 1):
			if self.marked[path[i][0]][path[i][1]] == 1:
				self.marked[path[i][0]][path[i][1]] = 0
			else:
				self.marked[path[i][0]][path[i][1]] = 1

	def __clear_covers(self) -> None:
		for i in range(self.n):
			self.row_covered[i] = False
			self.col_covered[i] = False

	def __erase_primes(self) -> None:
		for i in range(self.n):
			for j in range(self.n):
				if self.marked[i][j] == 2:
					self.marked[i][j] = 0

def make_cost_matrix(profit_matrix: Matrix, inversion_function: Optional[Callable[[AnyNum], AnyNum]]=None) -> Matrix:
	if not inversion_function:
		maximum = max((max(row) for row in profit_matrix))
		inversion_function = lambda x: maximum - x
	cost_matrix = []
	for row in profit_matrix:
		cost_matrix.append([inversion_function(value) for value in row])
	return cost_matrix

def print_matrix(matrix: Matrix, msg: Optional[str]=None) -> None:
	import math
	if msg is not None:
		print(msg)
	width = 0
	for row in matrix:
		for val in row:
			if val is DISALLOWED:
				val = DISALLOWED_PRINTVAL
			width = max(width, len(str(val)))
	format = '%%%d' % width
	for row in matrix:
		sep = '['
		for val in row:
			if val is DISALLOWED:
				val = DISALLOWED_PRINTVAL
			formatted = (format + 's') % val
			sys.stdout.write(sep + formatted)
			sep = ', '
		sys.stdout.write(']\n')

def solve_(lst):
	max_idx = len(lst) * 3 // 2 + 1
	matrix = []
	for a in lst:
		row = (list(range(a))[::-1] + list(range(1, max_idx)))[:max_idx]
		matrix.append(row)
	for _ in range(max_idx - len(lst)):
		row = [0] * max_idx
		matrix.append(row)
	m = Munkres()
	indexes = m.compute(matrix)
	total_cost = 0
	for (r, c) in indexes:
		x = matrix[r][c]
		total_cost += x
	return total_cost

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	pass
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def console(*args):
		pass

def solve(*args):
	console('----- solving ------')
	console(*args)
	console('----- ------- ------')
	return solve_(*args)
if True:
	inp = iter(sys.stdin.buffer.readlines())
	input = lambda : next(inp)
else:
	input = sys.stdin.buffer.readline
for case_num in range(int(input())):
	_ = int(input())
	lst = list(map(int, input().split()))
	lst = sorted(lst)
	res = solve(lst)
	print(res)


from math import inf
for _ in range(int(input())):
	n = int(input())
	a = sorted(map(int, input().split()))
	z = a[-1] + n + 1
	dp = [[inf for j in range(z)] for j in range(n + 1)]
	for i in range(z):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for j in range(i, z):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(j - a[i - 1]), dp[i][j - 1])
	print(min(dp[-1]))


t_p = int(input())
for _ in range(t_p):
	n = int(input())
	t = list(map(int, input().split()))
	t.sort()
	dp = [[100000 for j in range(2 * n + 2)] for i in range(n + 1)]
	for i in range(2 * n + 2):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for j in range(i, 2 * n + 2):
			dp[i][j] = min(dp[i][j], dp[i][j - 1], dp[i - 1][j - 1] + abs(j - t[i - 1]))
	print(dp[-1][-1])


q = int(input())
for query in range(q):
	n = int(input())
	t = [int(x) for x in input().split(' ')]
	t.sort()
	dp = [[float('inf')] * (2 * n + 1) for dish in range(n + 1)]
	for time in range(2 * n + 1):
		dp[0][time] = 0
	for i in range(1, n + 1):
		for j in range(1, 2 * n + 1):
			dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] + abs(t[i - 1] - j))
	print(dp[-1][-1])


import sys
sys.setrecursionlimit(10 ** 5)

def solve(curr_index, curr_time, arr, max_time):
	global memo
	if curr_time > max_time:
		return float('inf')
	if curr_index >= len(arr):
		return 0
	if (curr_index, curr_time) in memo:
		return memo[curr_index, curr_time]
	option1 = abs(arr[curr_index] - curr_time) + solve(curr_index + 1, curr_time + 1, arr, max_time)
	option2 = solve(curr_index, curr_time + 1, arr, max_time)
	ans = min(option1, option2)
	memo[curr_index, curr_time] = ans
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	arr = sorted(arr)
	max_time = 2 * n
	memo = {}
	print(solve(0, 1, arr, max_time))


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
inf = 10000000000

def solve(i, j, l, n, dp):
	if i == n:
		return 0
	if j > 2 * n:
		return inf
	if dp[i + 1, j + 1]:
		x = dp[i + 1, j + 1]
	else:
		dp[i + 1, j + 1] = solve(i + 1, j + 1, l, n, dp)
		x = dp[i + 1, j + 1]
	if dp[i, j + 1]:
		y = dp[i, j + 1]
	else:
		dp[i, j + 1] = solve(i, j + 1, l, n, dp)
		y = dp[i, j + 1]
	return min(abs(l[i] - j) + x, y)
while t:
	n = int(input())
	dp = dd(int)
	l = list(map(int, input().split()))
	l.sort()
	print(solve(0, 1, l, n, dp))
	t -= 1


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())
INF = 9999999999
for _ in range(II()):
	n = II()
	dp = [INF] * (2 * n + 1)
	dp[0] = 0
	for t in sorted(LI()):
		tmp = [INF] * (2 * n + 1)
		mn = INF
		for i in range(1, 2 * n + 1):
			mn = min(mn, dp[i - 1])
			tmp[i] = mn + abs(i - t)
		dp = tmp
	print(min(dp))


q = int(input())
for _ in range(q):
	n = int(input())
	ts = [t - 1 for t in map(int, input().split())]
	ts.sort()
	INF = 1000000000
	dp = [[INF] * 2 * n for _ in range(n + 1)]
	dp[0][0] = 0
	for i in range(n + 1):
		for j in range(2 * n - 1):
			if dp[i][j] < INF:
				if i < n:
					dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(ts[i] - j))
				dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	print(dp[n][2 * n - 1])


import sys
from array import array

def input():
	return sys.stdin.buffer.readline().decode('utf-8')
t = int(input())
ans = [0] * t
for _ in range(t):
	n = int(input())
	a = sorted(map(int, input().split()))
	inf = 10 ** 9
	dp = [[inf] * (n + 100) for _ in range(n + 1)]
	dp[0] = [0] * (n + 100)
	for i in range(n):
		cost = dp[i][0]
		for t in range(1, n + 100):
			dp[i + 1][t] = min(dp[i + 1][t], cost + abs(a[i] - t))
			cost = min(cost, dp[i][t])
	ans[_] = min(dp[-1])
print(*ans, sep='\n')


def solve(idx, T):
	if idx == n:
		return 0
	if T > 2 * n:
		return 100000000
	if dp[idx][T] != -1:
		return dp[idx][T]
	ans = 100000000
	ans = min(ans, solve(idx, T + 1))
	ans = min(ans, abs(T - l[idx]) + solve(idx + 1, T + 1))
	dp[idx][T] = ans
	return dp[idx][T]
t = int(input())
for _ in range(t):
	n = int(input())
	l = [int(x) for x in input().split()]
	l.sort()
	dp = [[-1 for i in range(500)] for j in range(500)]
	print(solve(0, 1))


INF = float('inf')
q = int(input())
for _ in range(q):
	n = int(input())
	dp = [[INF for ___ in range(2 * n + 1)] for __ in range(n)]
	t = list(sorted(map(int, input().split())))
	dp[0][1] = t[0] - 1
	for j in range(2, 2 * n):
		dp[0][j] = min(abs(t[0] - j), dp[0][j - 1])
	for i in range(1, n):
		for j in range(i + 1, 2 * n):
			dp[i][j] = min(abs(t[i] - j) + dp[i - 1][j - 1], dp[i][j - 1])
	print(min(dp[n - 1]))


for _ in range(int(input())):
	(n, values) = (int(input()), list(sorted([int(i) for i in input().split()])))
	dp = [[float('inf') for i in range(2 * n)] for j in range(n + 1)]
	dp[0][0] = 0
	for i in range(n + 1):
		for j in range(2 * n - 1):
			if dp[i][j] != float('inf') and i < n:
				dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(values[i] - 1 - j))
			dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	print(dp[n][2 * n - 1])


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 deque
tc = 1
tc = int(input())
for _ in range(tc):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [[-1 for i in range(405)] for j in range(n)]

	def solve(i, n, k):
		if i == n:
			return 0
		if k > 404:
			return float('inf')
		if dp[i][k] != -1:
			return dp[i][k]
		dp[i][k] = min(abs(k - a[i]) + solve(i + 1, n, k + 1), solve(i, n, k + 1))
		return dp[i][k]
	ans = solve(0, n, 1)
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	a = [0] + sorted(list(map(int, input().split())))
	d = [[1000000000.0 for _ in range(n + 1)] for _ in range(2 * n + 1)]
	d[0][0] = 0
	for i in range(1, 2 * n + 1):
		for j in range(0, n + 1):
			d[i][j] = min(d[i - 1][j], d[i - 1][j - 1] + abs(i - a[j]))
	ans = 1000000000.0
	for i in range(1, 2 * n + 1):
		ans = min(ans, d[i][n])
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(0)
	else:
		a.sort()
		dp = [[10 ** 10] * (2 * n + 1) for i in range(n + 1)]
		for i in range(2 * n + 1):
			dp[0][i] = 0
		for i in range(n + 1):
			dp[i][0] = 0
		for j in range(1, 2 * n + 1):
			dp[1][j] = abs(a[0] - j)
		for i in range(2, n + 1):
			for j in range(i, 2 * n + 1):
				for k in range(1, j):
					dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(a[i - 1] - j))
		print(min(dp[-1][1:]))


def f(arr):
	arr = list(map(lambda s: s - 1, arr))
	arr = sorted(arr)
	dp = [[float('inf')] * (2 * len(arr) + 1) for i in range(0, len(arr) + 1)]
	dp[0][0] = 0
	for i in range(0, len(arr) + 1):
		for j in range(2 * len(arr) - 1):
			if dp[i][j] != float('inf'):
				if i < len(arr):
					dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(arr[i] - j))
				dp[i][j + 1] = min(dp[i][j + 1], dp[i][j])
	return dp[len(arr)][2 * len(arr) - 1]
for i in range(int(input())):
	a = input()
	lst = list(map(int, input().strip().split()))
	print(f(lst))


from functools import lru_cache

@lru_cache(None)
def fun(time, taken):
	global ls
	global n
	if time > 2 * n + 5:
		return 100000000
	if taken == n:
		return 0
	minimum = 100000000
	minimum = min(minimum, abs(ls[taken] - time) + fun(time + 1, taken + 1))
	minimum = min(minimum, fun(time + 1, taken))
	return minimum
t = int(input())
ls = []
n = 0
for _ in range(t):
	n = int(input())
	ls = list(map(int, input().split()))
	ls = sorted(ls)
	print(fun(1, 0))
	fun.cache_clear()


from sys import maxsize
for _ in range(int(input())):
	n = int(input())
	ls = sorted(list(map(int, input().split())))
	dp = [[maxsize for i in range(2 * n + 1)] for j in range(n)]
	for i in range(1, 2 * n + 1):
		dp[0][i] = abs(i - ls[0])
	for i in range(1, n):
		mn = maxsize
		for j in range(1, 2 * n + 1):
			dp[i][j] = mn + abs(ls[i] - j)
			mn = min(mn, dp[i - 1][j])
	print(min(dp[n - 1]))


for _ in range(int(input())):
	n = int(input())
	t = sorted(list(map(int, input().split())))
	dp = [[0 for i in range(2 * n + 1)] for j in range(n + 1)]
	for i in range(n + 1):
		for j in range(2 * n + 1):
			if i == 0:
				dp[i][j] = 0
			else:
				dp[i][j] = float('inf')
	for i in range(1, n + 1):
		for j in range(1, 2 * n + 1):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(t[i - 1] - j), dp[i][j - 1])
	print(int(dp[n][2 * n]))


n = 0
dp = [[-1 for _ in range(210 * 2)] for _ in range(210)]
a = []

def solve(idx, time):
	if idx >= n:
		return 0
	if time > 2 * n:
		return 1000000000.0
	if dp[idx][time] != -1:
		return dp[idx][time]
	dp[idx][time] = 1000000000.0
	dp[idx][time] = min(dp[idx][time], solve(idx, time + 1))
	dp[idx][time] = min(dp[idx][time], solve(idx + 1, time + 1) + abs(time - a[idx]))
	return dp[idx][time]
Q = int(input())
for _ in range(Q):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	for i in range(len(dp)):
		for j in range(len(dp[0])):
			dp[i][j] = -1
	print(solve(0, 1))


from functools import lru_cache
INF = 10 ** 9
for _ in range(int(input())):
	nn = int(input())
	a = [0] + list(map(int, input().split()))
	a.sort()

	@lru_cache(maxsize=None)
	def f(n, k):
		if n < 0 or k < 0:
			return INF
		if n == 0 and k == 0:
			return 0
		return min(f(n, k - 1), f(n - 1, k - 1) + abs(a[n] - k))
	print(f(nn, 410))


from sys import setrecursionlimit
setrecursionlimit(10 ** 5)
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	arr.sort()
	d = {}

	def helper(curr, t):
		if curr == n:
			return 0
		if t > 2 * n:
			return 1000000000
		if (curr, t) in d:
			return d[curr, t]
		ans = min(abs(t - arr[curr]) + helper(curr + 1, t + 1), helper(curr, t + 1))
		d[curr, t] = ans
		return ans
	print(helper(0, 1))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

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

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

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

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

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	ma = l[-1]
	dp = [[999999 for i in range(ma + n + 1)] for j in range(n)]
	for i in range(1, ma + n + 1):
		dp[0][i] = abs(l[0] - i)
	for i in range(1, n):
		for j in range(1, ma + n + 1):
			for k in range(1, j):
				dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(l[i] - j))
	print(min(dp[-1]))


import sys
original_stdout = sys.stdout
var_for_sublime = False
if var_for_sublime:
	fin = open('input.txt', 'r')
	fout = open('output.txt', 'w')
	sys.stdout = fout

	def give_string():
		return fin.readline()
else:
	fin = sys.stdin
	fout = sys.stdout

	def give_string():
		return fin.buffer.readline()

def give_list():
	return list(map(int, give_string().split()))

def give_int():
	return int(give_string())
MOD = 1000000000.0 + 7

def modpow(a, p):
	ans = 1
	while p:
		if p & 1:
			ans *= a
			ans %= MOD
		p >>= 1
		a *= a
		a %= MOD
	return ans

def fac_cal(n):
	ans = 1
	for i in range(1, n + 1):
		ans *= i
		ans %= MOD
	return ans

def solve():
	n = give_int()
	t = give_list()
	t.sort()
	dp = [[1000000000.0] * (2 * n) for i in range(n)]
	for i in range(n):
		for j in range(i + 1, 2 * n):
			if i == 0:
				dp[i][j] = min(dp[i][j - 1], abs(t[0] - j))
			else:
				dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] + abs(t[i] - j))
	ans = 1000000000.0
	for i in range(2 * n):
		ans = min(ans, dp[n - 1][i])
	print(ans)

def main():
	try:
		t = 1
		t = give_int()
		for i in range(t):
			solve()
	finally:
		fin.close()
		fout.close()
		sys.stdout = original_stdout
main()


import sys
input = sys.stdin.readline

def main():
	for j in range(int(input())):
		n = int(input())
		vals = sorted(map(int, input().split()))
		dp = [[10 ** 5 for s in range(n + 1)] for s in range(2 * n + 1)]
		dp[0][0] = 0
		for s in range(1, 2 * n + 1):
			for i in range(1, n + 1):
				dp[s][i] = min(dp[s - 1][i - 1] + abs(s - vals[i - 1]), dp[s - 1][i])
				dp[s][i - 1] = min(dp[s - 1][i - 1], dp[s][i - 1])
		minans = 10 ** 5
		for s in range(2 * n + 1):
			minans = min(minans, dp[s][n])
		print(minans)
main()


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	v = list(map(int, input().split()))
	vx = sorted(v)
	INF = 1000000000.0
	dp = [[INF for i in range(2 * n + 1)] for j in range(n + 1)]
	for j in range(2 * n + 1):
		dp[0][j] = 0
	for i in range(1, n + 1):
		for j in range(1, 2 * n + 1):
			dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] + abs(j - vx[i - 1]))
	print(dp[n][2 * n])


from sys import stdin, stdout

def II():
	return int(stdin.readline())

def LI():
	return list(map(int, stdin.readline().split()))
dp = []

def findAns(idx, tnow, n, t):
	global dp
	if idx == n:
		return 0
	if tnow == 2 * n:
		return 10 ** 7
	if dp[idx][tnow] != -1:
		return dp[idx][tnow]
	dp[idx][tnow] = min(abs(t[idx] - tnow) + findAns(idx + 1, tnow + 1, n, t), findAns(idx, tnow + 1, n, t))
	return dp[idx][tnow]

def solve():
	global dp
	n = II()
	t = LI()
	t.sort()
	dp = [[-1 for i in range(2 * n)] for j in range(n)]
	ans = findAns(0, 1, n, t)
	stdout.write(str(ans) + '\n')
q = II()
for _ in range(q):
	solve()


import random
import sys
import os
xt = int(input())
for q in range(xt):
	n = int(input())
	b = list(map(int, input().strip().split()))[:n]
	a = [0] * n * 2
	for i in range(0, n, 1):
		a[i + 1] = b[i]
	a[1:n + 1] = sorted(a[1:n + 1])
	ans = 1000 * 1000 * 1000 + 5
	dp = [[ans for i in range(0, 2 * n + 5, 1)] for j in range(0, 2 * n + 5, 1)]
	for t in range(1, 2 * n + 1, 1):
		dp[t][1] = abs(a[1] - t)
		if n == 1:
			ans = min(ans, dp[t][1])
	for i in range(2, n + 1, 1):
		for t in range(1, 2 * n + 1, 1):
			for tt in range(1, t, 1):
				dp[t][i] = min(dp[t][i], dp[tt][i - 1] + abs(t - a[i]))
				if i == n:
					ans = min(ans, dp[t][i])
	print(ans)


mod = 10 ** 9
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = set()
	a.sort()
	m = max(a)
	dp = [[10 ** 9 for i in range(m + n + 1)] for j in range(n)]
	for i in range(1, m + n + 1):
		dp[0][i] = abs(i - a[0])
	for i in range(1, n):
		for j in range(1, m + n + 1):
			for k in range(1, j):
				d = abs(a[i] - j)
				dp[i][j] = min(dp[i][j], dp[i - 1][k] + d)
	m = 10 ** 18
	m = min(dp[-1])
	print(m)


def dps(index, t):
	if dp[index][t] != -1:
		return dp[index][t]
	if index == 0:
		return max(0, t - time[0])
	if t < time[index]:
		dp[index][t] = min(dps(index, t + 1), dps(index - 1, t + 1) + abs(t - time[index]))
		return dp[index][t]
	else:
		dp[index][t] = dps(index - 1, t + 1) + abs(t - time[index])
		return dp[index][t]
for _ in range(int(input())):
	n = int(input())
	time = list(map(int, input().split()))
	time.sort(reverse=True)
	dp = list()
	for i in range(n):
		temp = [-1 for j in range(2 * (n + 1))]
		dp.append(temp)
	print(dps(n - 1, 1))


from collections import deque, defaultdict

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	dp = [0] * (2 * n + 1)
	for i in range(n):
		if i == 0:
			mi = 0
		else:
			mi = dp[i]
		dp2 = [0] * (2 * n + 1)
		for j in range(i + 1, i + n + 1):
			dp2[j] = mi + abs(a[i] - j)
			mi = min(mi, dp[j])
		dp = dp2.copy()
	if len(dp) > 1:
		print(min(dp[n:2 * n]))
	else:
		print(0)

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


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	t = sorted(map(int, input().split()))
	cur = [0] * (2 * n)
	for i in range(n):
		low = high = t[i]
		while low and cur[low]:
			low -= 1
		while cur[high]:
			high += 1
		if low > 0 and i:
			lowsum = ind = j = 0
			cur[low] = 1
			while ind <= i:
				if cur[j]:
					lowsum += abs(t[ind] - j)
					ind += 1
				j += 1
			cur[low] = 0
			highsum = ind = j = 0
			cur[high] = 1
			while ind <= i:
				if cur[j]:
					highsum += abs(t[ind] - j)
					ind += 1
				j += 1
			cur[high] = 0
			if lowsum < highsum:
				cur[low] = 1
			else:
				cur[high] = 1
		else:
			cur[high] = 1
	ans = ind = j = 0
	while ind < n:
		if cur[j]:
			ans += abs(t[ind] - j)
			ind += 1
		j += 1
	print(ans)


T = int(input())
while T > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	dp = [[0 for i in range(arr[-1] + 1)] for j in range(n + 1)]
	su = []
	s = 0
	for i in range(n):
		s += arr[i]
		su.append(s)
	for i in range(n - 1, -1, -1):
		for j in range(len(dp[0]) - 1, 0, -1):
			if j == arr[-1]:
				dp[i][j] = (arr[-1] * 2 + n - i - 1) * (n - i) // 2 - su[-1]
				if i > 0:
					dp[i][j] += su[i - 1]
			else:
				dp[i][j] = min(dp[i][j + 1], abs(arr[i] - j) + dp[i + 1][j + 1])
	res = float('inf')
	for i in range(1, arr[-1] + 1):
		res = min(res, dp[0][i])
	print(res)
	T -= 1


for _ in range(int(input())):
	_ = int(input())
	(*t,) = map(int, input().split())
	t.sort()
	inf = float('inf')
	n = len(t) * 2 + 10
	dp = [[inf] * n for _ in range(len(t) + 1)]
	for i in range(n):
		dp[0][i] = 0
	for i in range(len(t)):
		for prev_t in range(n):
			for next_t in range(prev_t + 1, n):
				if dp[i][prev_t] != inf:
					dp[i + 1][next_t] = min(dp[i + 1][next_t], dp[i][prev_t] + abs(next_t - t[i]))
	print(min(dp[len(t)]))


T = int(input())
for _ in range(T):
	(n, tm) = (int(input()), list(sorted(map(int, input().split()))))
	dp = [[n * n] * (2 * n + 1) for i in range(n + 1)]
	for i in range(2 * n + 1):
		dp[0][i] = 0
	for dish in range(1, n + 1):
		for time in range(1, 2 * n + 1):
			for prev in range(time):
				cur = dp[dish - 1][prev] + abs(tm[dish - 1] - time)
				dp[dish][time] = min(cur, dp[dish][time])
	print(min([dp[n][i] for i in range(2 * n + 1)]))


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	dp = [[0] * (n + 1) for _ in range(2 * (n + 1))]
	dp[0] = [1000000] * (2 * (n + 1))
	dp[0][0] = 0
	for i in range(1, 2 * (n + 1)):
		for j in range(1, n + 1):
			dp[i][j] = min(dp[i - 1][j - 1] + abs(a[j - 1] - i), dp[i - 1][j])
	print(dp[-1][n])


import sys, string
from collections import deque, defaultdict
from math import sqrt, factorial, gcd, ceil, atan, pi, log2

def input():
	return sys.stdin.buffer.readline().decode('utf-8')
from bisect import bisect_left, bisect_right
from operator import add
MOD = int(1000000000.0) + 7
INF = float('inf')

def solve():
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	dp = [[INF for _ in range(444)] for _ in range(444)]
	dp[0][0] = 0
	for items in range(1, n + 1):
		for time in range(1, 444):
			dp[0][time] = 0
			dp[items][time] = min(dp[items][time], dp[items][time - 1])
			dp[items][time] = min(dp[items][time], dp[items - 1][time - 1] + abs(time - a[items - 1]))
	print(min(dp[n]))
T = 1
T = int(input())
for case in range(1, T + 1):
	ans = solve()


t = int(input())
while t:
	t -= 1
	n = int(input())
	l = list(map(int, input().split(' ')))
	l.sort()
	l.insert(0, 0)
	dp = [[int(1e+18) for _ in range(2 * n + 1)] for _ in range(2 * n + 1)]
	for i in range(0, n * 2 + 1):
		dp[0][i] = 0
	for i in range(1, n + 1):
		for j in range(1, n * 2 + 1):
			dp[i][j] = abs(l[i] - j) + dp[i - 1][j - 1]
			dp[i][j] = min(dp[i][j - 1], dp[i][j])
	print(dp[n][n * 2])


import bisect
import math
import collections
import sys
input = sys.stdin.readline

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

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

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

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

def solution():
	n = inp()
	for _ in range(n):
		k = inp()
		a = inlt()
		print(solve(a, k))

def solve(a, k):
	dp = [[0] * 401 for _ in range(k)]
	for (i, num) in enumerate(sorted(a)):
		if i == 0:
			for t in range(1, num):
				dp[i][t] = num - t
			continue
		dp[i][i] = float('inf')
		for t in range(i + 1, 401):
			dp[i][t] = min(dp[i - 1][t - 1] + abs(num - t), dp[i][t - 1])
	return dp[-1][-1]
solution()


INF = 4557430888798830399
q = int(input())
for _ in range(q):
	n = int(input())
	t = [0] + list(map(int, input().split()))
	t.sort()
	m = n * 2
	dp = [[0] * (m + 1)] + [[INF] * (m + 1) for _ in range(n)]
	for i in range(1, n + 1):
		for j in range(1, m + 1):
			dp[i][j] = min(dp[i][j], dp[i][j - 1], dp[i - 1][j - 1] + abs(j - t[i]))
	print(dp[n][m])


import sys, math
input = sys.stdin.readline
t = int(input())
for r in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	dp = []
	for i in range(n + 1):
		temp = [0] * (2 * n + 1)
		dp.append(temp)
	for i in range(1, n + 1):
		for j in range(1, 2 * n + 1):
			temp = 99999999999999999999999999
			start = 1
			if i == 1:
				start = 0
			for k in range(start, j):
				temp = min(temp, dp[i - 1][k])
			dp[i][j] = abs(l[i - 1] - j) + temp
	ans = 999999999999999999999999999
	for i in range(1, 2 * n + 1):
		ans = min(ans, dp[n][i])
	print(ans)


from sys import stdin, stdout

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

def inp():
	return stdin.readline()

def out(x):
	return stdout.write(x)
import math as M
MOD = 10 ** 9 + 7
from random import randint as R

def calc(ind, t, n, A, dp):
	if ind == n:
		return 0
	if t == 2 * n + 1:
		return 10 ** 9
	if dp[ind][t] != -1:
		return dp[ind][t]
	ans = 10 ** 9
	ans = min(ans, calc(ind, t + 1, n, A, dp))
	ans = min(ans, abs(t - A[ind]) + calc(ind + 1, t + 1, n, A, dp))
	dp[ind][t] = ans
	return ans
for _ in range(int(input())):
	n = int(input())
	A = INPUT()
	dp = [[-1 for i in range(2 * n + 1)] for i in range(n)]
	A.sort()
	print(calc(0, 1, n, A, dp))


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	dp = [[int(1000000000.0) for i in range(3 * n)] for j in range(2 * n + 2)]
	dp[1][0] = 0
	res = 1000000000.0
	for i in range(1, 2 * n + 1):
		for j in range(n):
			dp[i + 1][j] = min(dp[i][j], dp[i + 1][j])
			dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(a[j] - i))
		res = min(res, dp[i][n])
	print(res)