## https://yukicoder.me/problems/no/2665 from collections import deque class BinaryIndexTree: """ フェニック木(BinaryIndexTree)の基本的な機能を実装したクラス """ def __init__(self, size): self.size = size self.array = [0] * (size + 1) def add(self, x, a): index = x while index <= self.size: self.array[index] += a index += index & (-index) def sum(self, x): index = x ans = 0 while index > 0: ans += self.array[index] index -= index & (-index) return ans def least_upper_bound(self, value): if self.sum(self.size) < value: return -1 elif value <= 0: return 0 m = 1 while m < self.size: m *= 2 k = 0 k_sum = 0 while m > 0: k0 = k + m if k0 < self.size: if k_sum + self.array[k0] < value: k_sum += self.array[k0] k += m m //= 2 if k < self.size: return k + 1 else: return -1 def solve(n, P): bit = BinaryIndexTree(n) queue = deque() answer = 0 for p in P: if len(queue) == 0: queue.append(p) bit.add(p, 1) else: back = len(queue) - bit.sum(p) front = bit.sum(p) if front >= back: queue.append(p) answer += back else: queue.appendleft(p) answer += front bit.add(p, 1) array = [] while len(queue) > 0: array.append(queue.popleft()) return [ answer, " ".join(map(str, array)) ] def main(): T = int(input()) answers = [] for _ in range(T): n = int(input()) P = list(map(int, input().split())) ans = solve(n, P) answers.append(ans) for ans in answers: print(ans[0]) print(ans[1]) if __name__ == "__main__": main()