for~ else문을 사용했다.
for ~ else문은 for문을 모두 돌 때까지 break가 되지 않으면 else 구문이 실행되는 형태이다.
for tc in range(1,int(input())+1):
N,M = map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(M)]
res=arr.pop(0)
for i in arr:
chk=i[0]
for j in range(len(res)):
if chk<res[j]:
res[j:j]=i
break
else:
res.extend(i)
if len(res)>10:
res=res[-1:-10-1:-1]
else:
arr[::-1]
print(f'#{tc}', end=' ')
print(*res)