def DFS(a, vert):
visited = []
order = []
arr = [a]
while arr:
curr = arr.pop()
if curr not in visited:
visited.append(curr)
order.append(curr)
arr.extend(sorted(vert[curr], reverse=True))
return " ".join(map(str, order)) + "\n"
def BFS(a, vert):
visited = []
order = []
arr = [a]
while arr:
curr = arr.pop(0)
if curr not in visited:
visited.append(curr)
order.append(curr)
arr.extend(sorted(vert[curr]))
return " ".join(map(str, order)) + "\n"
output = ""
counter = 1
for t in range(int(input())):
output += f"graph {counter}\n"
mapOfAngels = {}
for n in range(int(input())):
p = input().split()
i = int(p[0])
m = int(p[1])
w = []
c2 = 2
for wc in range(m):
w.append(int(p[c2]))
c2 += 1
mapOfAngels[i] = w
while True:
p2 = input().split()
a = int(p2[0])
method = int(p2[1])
if a == 0 and method == 0:
break
if method == 0:
output += DFS(a, mapOfAngels)
pass
elif method == 1:
output += BFS(a, mapOfAngels)
pass
counter += 1
print(output)
ZGVmIERGUyhhLCB2ZXJ0KToKICAgIHZpc2l0ZWQgPSBbXQogICAgb3JkZXIgPSBbXQogICAgYXJyID0gW2FdCgogICAgd2hpbGUgYXJyOgogICAgICAgIGN1cnIgPSBhcnIucG9wKCkKICAgICAgICBpZiBjdXJyIG5vdCBpbiB2aXNpdGVkOgogICAgICAgICAgICB2aXNpdGVkLmFwcGVuZChjdXJyKQogICAgICAgICAgICBvcmRlci5hcHBlbmQoY3VycikKICAgICAgICAgICAgYXJyLmV4dGVuZChzb3J0ZWQodmVydFtjdXJyXSwgcmV2ZXJzZT1UcnVlKSkKCiAgICByZXR1cm4gIiAiLmpvaW4obWFwKHN0ciwgb3JkZXIpKSArICJcbiIKCmRlZiBCRlMoYSwgdmVydCk6CiAgICB2aXNpdGVkID0gW10KICAgIG9yZGVyID0gW10KICAgIGFyciA9IFthXQoKICAgIHdoaWxlIGFycjoKICAgICAgICBjdXJyID0gYXJyLnBvcCgwKQogICAgICAgIGlmIGN1cnIgbm90IGluIHZpc2l0ZWQ6CiAgICAgICAgICAgIHZpc2l0ZWQuYXBwZW5kKGN1cnIpCiAgICAgICAgICAgIG9yZGVyLmFwcGVuZChjdXJyKQogICAgICAgICAgICBhcnIuZXh0ZW5kKHNvcnRlZCh2ZXJ0W2N1cnJdKSkKCiAgICByZXR1cm4gIiAiLmpvaW4obWFwKHN0ciwgb3JkZXIpKSArICJcbiIKCm91dHB1dCA9ICIiCmNvdW50ZXIgPSAxCgpmb3IgdCBpbiByYW5nZShpbnQoaW5wdXQoKSkpOgogICAgb3V0cHV0ICs9IGYiZ3JhcGgge2NvdW50ZXJ9XG4iCiAgICBtYXBPZkFuZ2VscyA9IHt9CiAgICBmb3IgbiBpbiByYW5nZShpbnQoaW5wdXQoKSkpOgogICAgICAgIHAgPSBpbnB1dCgpLnNwbGl0KCkKICAgICAgICBpID0gaW50KHBbMF0pCiAgICAgICAgbSA9IGludChwWzFdKQogICAgICAgIHcgPSBbXQoKICAgICAgICBjMiA9IDIKICAgICAgICBmb3Igd2MgaW4gcmFuZ2UobSk6CiAgICAgICAgICAgIHcuYXBwZW5kKGludChwW2MyXSkpCiAgICAgICAgICAgIGMyICs9IDEKCiAgICAgICAgbWFwT2ZBbmdlbHNbaV0gPSB3CiAgICAgICAgCiAgICB3aGlsZSBUcnVlOgogICAgICAgIHAyID0gaW5wdXQoKS5zcGxpdCgpCiAgICAgICAgYSA9IGludChwMlswXSkKICAgICAgICBtZXRob2QgPSBpbnQocDJbMV0pCiAgICAgICAgaWYgYSA9PSAwIGFuZCBtZXRob2QgPT0gMDoKICAgICAgICAgICAgYnJlYWsKCiAgICAgICAgaWYgbWV0aG9kID09IDA6CiAgICAgICAgICAgIG91dHB1dCArPSBERlMoYSwgbWFwT2ZBbmdlbHMpCiAgICAgICAgICAgIHBhc3MKICAgICAgICBlbGlmIG1ldGhvZCA9PSAxOgogICAgICAgICAgICBvdXRwdXQgKz0gQkZTKGEsIG1hcE9mQW5nZWxzKQogICAgICAgICAgICBwYXNzCgogICAgY291bnRlciArPSAxCgpwcmludChvdXRwdXQp
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