from collections import deque from atcoder.fenwicktree import FenwickTree for _ in range(int(input())): n = int(input()) P = list(map(int, input().split())) fw = FenwickTree(n) q = deque([]) ans = 0 for i in P: a = fw.sum(0, i - 1) b = fw.sum(i, n) ans += min(a, b) if a < b: q.appendleft(i) elif a > b: q.append(i) else: if q: l = q.popleft() q.appendleft(l) if i < l: q.appendleft(i) else: q.append(i) else: q.append(i) fw.add(i-1, 1) print(ans) print(*list(q))