import sys, time, random from collections import deque, Counter, defaultdict input = lambda: sys.stdin.readline().rstrip() ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) inf = 2 ** 61 - 1 mod = 998244353 class fenwick_tree(): n=1 data=[0 for i in range(n)] def __init__(self,N): self.n=N self.data=[0 for i in range(N)] def add(self,p,x): assert 0<=p0): s+=self.data[r-1] r-=r&-r return s def __getitem__(self, p): if isinstance(p, int): return self.sum(p, p + 1) else: return self.sum(p.start, p.stop) def __setitem__(self, p, x): return self.add(p, x - self[p]) def solve(): n = ii() a = li() f = fenwick_tree(n + 1) ans = deque() cnt = 0 for i in range(n): if f.sum(0, a[i]) < f.sum(a[i] + 1, n + 1): ans.appendleft(a[i]) cnt += f.sum(0, a[i]) else: ans.append(a[i]) cnt += f.sum(a[i] + 1, n + 1) f.add(a[i], 1) print(cnt) print(*ans) for _ in range(ii()): solve()