from itertools import product # library from https://prd-xxx.hateblo.jp/entry/2020/02/07/114818 class Deque: def __init__(self, src_arr=[], max_size=300000): self.N = max(max_size, len(src_arr)) + 1 self.buf = list(src_arr) + [None] * (self.N - len(src_arr)) self.head = 0 self.tail = len(src_arr) def __index(self, i): l = len(self) if not -l <= i < l: raise IndexError('index out of range: ' + str(i)) if i < 0: i += l return (self.head + i) % self.N def __extend(self): ex = self.N - 1 self.buf[self.tail+1 : self.tail+1] = [None] * ex self.N = len(self.buf) if self.head > 0: self.head += ex def is_full(self): return len(self) >= self.N - 1 def is_empty(self): return len(self) == 0 def append(self, x): if self.is_full(): self.__extend() self.buf[self.tail] = x self.tail += 1 self.tail %= self.N def appendleft(self, x): if self.is_full(): self.__extend() self.buf[(self.head - 1) % self.N] = x self.head -= 1 self.head %= self.N def pop(self): if self.is_empty(): raise IndexError('pop() when buffer is empty') ret = self.buf[(self.tail - 1) % self.N] self.tail -= 1 self.tail %= self.N return ret def popleft(self): if self.is_empty(): raise IndexError('popleft() when buffer is empty') ret = self.buf[self.head] self.head += 1 self.head %= self.N return ret def __len__(self): return (self.tail - self.head) % self.N def __getitem__(self, key): return self.buf[self.__index(key)] def __setitem__(self, key, value): self.buf[self.__index(key)] = value def __str__(self): return 'Deque({0})'.format(str(list(self))) class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): assert i != 0 s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i <= self.size: self.tree[i] += x i += i & -i def solve(): n = int(input()) plist = list(map(int, input().split())) deq = Deque() bit = Bit(n+10) tento = 0 for i in range(n): p = plist[i] # print(p) if i == 0: deq.append(p) bit.add(p,1) continue low = bit.sum(p) up = i-low # print(p, low, up) if low > up: deq.append(p) tento += up elif low == up: if deq[0] < p: deq.append(p) tento += up else: deq.appendleft(p) tento += low else: deq.appendleft(p) tento += low bit.add(p, 1) # print(deq) print(tento) print(*deq) q = int(input()) while q: q -= 1 solve()