from bisect import * def lis(A): B = []; I = []; P = [-1]*len(A) for i, e in enumerate(A): p = bisect(B, e-1) if p: P[i] = I[p-1] if p == len(B): B.append(e); I.append(i) else: B[p] = e; I[p] = i Z = []; i = I[-1] while i >= 0: Z += A[i],; i = P[i] return Z[::-1] def merge(a, b): z = [] while a and b: if a[-1] < b[-1]: z += a.pop(), else: z += b.pop(), while a: z += a.pop(), while b: z += b.pop(), return z[::-1] for _ in range(int(input())): N, K = map(int, input().split()) Z = []; C = []; I = []; B = [0]*-~N; P = [0]*-~N for b in range(K): _, *v = map(int, input().split()) L = lis(v); S = {*L} R = [i for i in v if i not in S] for e, i in enumerate(v): P[i] = e; B[i] = b Z += L[::-1],; C += R[::-1],; I += P, while len(Z) > 1: U = [] while len(Z) > 1: U += merge(Z.pop(), Z.pop()), if Z: U += Z.pop(), Z = U W = [] for i in Z[0][::-1]: b = B[i] while C[b] and P[C[b][-1]] < P[i]: W += C[b].pop(), W += i, print(*W, *sum([c[::-1] for c in C], []))