from collections import deque def segfunc(x, y): return x + y class SegTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.n = n self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def __getitem__(self, n): return self.tree[self.num+n] def List(self): return self.tree[self.num:self.num+self.n] T = int(input()) for _ in range(T): N = int(input()) P = list(map(int, input().split())) seg = SegTree([0]*N, segfunc, 0) seg.update(P[0]-1, 1) que = deque([P[0]]) inversion = 0 for i in range(1, N): big, small = 0, 0 if 2 <= P[i]: small = seg.query(0, P[i]-1) if P[i] < N: big = seg.query(P[i], N) if small < big: que.appendleft(P[i]) inversion += small elif small > big: que.append(P[i]) inversion += big else: if P[i] < que[0]: que.appendleft(P[i]) else: que.append(P[i]) inversion += small seg.update(P[i]-1, 1) print(inversion) print(*list(que))