//状态压缩 和hdu 1074 Doing Homework 几乎一样
#include <iostream>
#define MAXN 12
using namespace std;
struct Node {
int val;
int r[MAXN];
};
Node dp[1<<MAXN], q;
bool f[1<<MAXN];
int n = 10, num;
void res() {
dp[ 0 ].val = 0;
memset(f, false, sizeof(f));
f[ 0 ] = true;
int cnt = (1 << (n - 1)) - 1;
for(int j = 0; j < cnt; ++ j) {
for(int i = 0; i < n - 1; ++ i) {
int val = 1 << i;
if(!(val & j)) {
int tmp = val | j;
for(int k = 0; k < n; ++ k) {
q.r[ k ] = dp[ j ].r[ k ];
}
int tt = abs(q.r[ i ] - q.r[i + 1]);
if(tt == 0) continue;
if(f[ tmp ]) {
if(dp[ j ].val + tt < dp[ tmp ].val) {
q.val = dp[ j ].val + tt;
int cc = q.r[ i ];
for(int g = 0; g < n; ++ g) {
if(q.r[ g ] == cc) {
q.r[ g ] = q.r[i + 1];
}
}
dp[ tmp ] = q;
// printf("t %d %d\n", tmp, dp[ tmp ].val);
}
}
else {
f[ tmp ] = true;
q.val = dp[ j ].val + tt;
int cc = q.r[ i ];
for(int g = 0; g < n; ++ g) {
if(q.r[ g ] == cc) {
q.r[ g ] = q.r[i + 1];
}
}
dp[ tmp ] = q;
//printf("f %d %d\n", tmp, dp[ tmp ].val);
}
}
}
}
printf("%d\n", dp[ cnt ].val);
}
int main() {
int test;
scanf("%d", &test);
while(test --) {
for(int i = 0; i < n; ++ i) {
scanf("%d", &num);
dp[ 0 ].r[num - 1] = i;
}
res();
}
return 0;
}