import types _atcoder_code = """ # Python port of AtCoder Library. __version__ = '0.0.1' """ atcoder = types.ModuleType('atcoder') exec(_atcoder_code, atcoder.__dict__) _atcoder_fenwicktree_code = """ import typing class FenwickTree: '''Reference: https://en.wikipedia.org/wiki/Fenwick_tree''' def __init__(self, n: int = 0) -> None: self._n = n self.data = [0] * n def add(self, p: int, x: typing.Any) -> None: assert 0 <= p < self._n p += 1 while p <= self._n: self.data[p - 1] += x p += p & -p def sum(self, left: int, right: int) -> typing.Any: assert 0 <= left <= right <= self._n return self._sum(right) - self._sum(left) def _sum(self, r: int) -> typing.Any: s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s """ atcoder.fenwicktree = types.ModuleType('atcoder.fenwicktree') exec(_atcoder_fenwicktree_code, atcoder.fenwicktree.__dict__) FenwickTree = atcoder.fenwicktree.FenwickTree # from atcoder.fenwicktree import FenwickTree from collections import deque T = int(input()) def solve(n, P): ft = FenwickTree(n+1) ans = deque() cnt = 0 for p in P: s = ft.sum(0, p) g = ft.sum(p+1, n+1) if s < g: ans.appendleft(p) cnt += s elif s > g: ans.append(p) cnt += g else: if len(ans) == 0: ans.appendleft(p) cnt += s else: if p < ans[0]: ans.appendleft(p) cnt += s else: ans.append(p) cnt += g ft.add(p, 1) print(cnt) print(*ans) for _ in range(T): n = int(input()) P = list(map(int, input().split())) solve(n, P)