class FenwickTree: def __init__(self, iterable): self.tree = tree = [0] tree.extend(iterable) self.data = tree[1:] self.N = N = len(tree) - 1 for i in range(1, N+1): if i + (i& -i) <= N: tree[i + (i& -i)] += tree[i] def add(self, i, x): assert 0 <= i < self.N tree = self.tree self.data[i] += x i += 1 while i <= self.N: tree[i] += x i += i& -i def sum(self, l, r): assert 0 <= l <= r <= self.N tree = self.tree res = 0 while l < r: res += tree[r] r &= r-1 while l > r: res -= tree[l] l &= l-1 return res def __repr__(self): return repr(self.data) from collections import deque T = int(input()) for _ in range(T): N = int(input()) P = list(map(lambda x: int(x) - 1, input().split())) fw = FenwickTree([0]*N) Q = deque() inv = 0 for i, p in enumerate(P): xL = fw.sum(0, p) xR = i-xL if xL > xR: Q.append(p) inv += xR if xL < xR: Q.appendleft(p) inv += xL if xL == xR: inv += xL if not Q: Q.append(p) else: if Q[0] > p: Q.appendleft(p) else: Q.append(p) fw.add(p, 1) print(inv) print(*(x+1 for x in Q))