All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $n\cdot m$ different seals, denoted by distinct numbers. All of them were written in an $n\times m$ table.

The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.


-----Input-----

The first line of the input contains the only integer $t$ ($1\leq t\leq 100\,000$) denoting the number of test cases. Their descriptions follow.

The first line of each test case description consists of two space-separated integers $n$ and $m$ ($1 \leq n, m \leq 500$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $1$ to $n\cdot m$.

The following $n$ lines contain $m$ space separated integers each, denoting elements of an arbitrary row in the table left to right.

The following $m$ lines contain $n$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom.

Sum of $nm$ over all test cases does not exceed $250\,000$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $1$ to $nm$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.


-----Output-----

For each test case, output $n$ lines with $m$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.


-----Example-----
Input
2
2 3
6 5 4
1 2 3
1 6
2 5
3 4
3 1
2
3
1
3 1 2

Output
1 2 3 
6 5 4 
3 
1 
2 



-----Note-----

Consider the first test case. The matrix is $2 \times 3$. You are given the rows and columns in arbitrary order.

One of the rows is $[6, 5, 4]$. One of the rows is $[1, 2, 3]$.

One of the columns is $[1, 6]$. One of the columns is $[2, 5]$. One of the columns is $[3, 4]$.

You are to reconstruct the matrix. The answer is given in the output.

Difficulty: EASY
Tags: Implementation

Starter code:

Solutions:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		row = tuple((tuple(map(int, input().split())) for _ in range(n)))
		col = tuple((tuple(map(int, input().split())) for _ in range(m)))
		row_nums = [0] * (n * m + 1)
		for i in range(n):
			for j in row[i]:
				row_nums[j] = i
		res = [[] for _ in range(n)]
		for i in range(n):
			vi = col[0][i]
			row_num = row_nums[vi]
			res[i] = row[row_num]
		for i in res:
			print(*i)
resolve()


import sys
input = sys.stdin.readline

def main():
	T = int(input())
	for t in range(T):
		(n, m) = map(int, input().split())
		rows = []
		columns = []
		for j in range(n):
			rows.append(list(map(int, input().split())))
		for j in range(m):
			columns.append(list(map(int, input().split())))
		tops = []
		for j in range(m):
			tops.append(columns[j][0])
		tops_sort = sorted(tops)
		mat = []
		for row in rows:
			sortedrow = sorted(row)
			if sortedrow == tops_sort:
				mat.append(row)
				break
		for j in range(n - 1):
			mat.append([0] * m)
		for (i, top) in enumerate(mat[0]):
			idx = tops.index(top)
			for j in range(1, n):
				mat[j][i] = columns[idx][j]
		for i in range(n):
			print(*mat[i])
main()


import sys
import math
import collections
import bisect
from collections import deque as queue

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	(n, m) = get_ints()
	row = []
	for i in range(n):
		row.append(get_list())
	col = []
	for i in range(m):
		col.append(get_list())
	ans = []
	row_no = dict()
	for i in range(n):
		for j in range(m):
			ele = row[i][j]
			row_no[ele] = i
	for i in range(n):
		ele = col[0][i]
		index_of_row = row_no[ele]
		ans.append(row[index_of_row])
	for i in ans:
		print(*i)


import sys as _sys

def main():
	t = int(input())
	for i_t in range(t):
		(rows_n, columns_n) = _read_ints()
		rows = [tuple(_read_ints()) for i_row in range(rows_n)]
		columns = [tuple(_read_ints()) for i_column in range(columns_n)]
		any_first_column_element = rows[0][0]
		i_first_column = 0
		while any_first_column_element not in columns[i_first_column]:
			i_first_column += 1
		first_column = columns[i_first_column]
		rows = sorted(rows, key=lambda row: first_column.index(row[0]))
		for row in rows:
			print(*row)

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return map(int, _read_line().split())
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	D = {}
	for i in range(n):
		line = list(map(int, input().split()))
		D[line[0]] = line
	res = []
	for i in range(m):
		colum = list(map(int, input().split()))
		if colum[0] in D:
			res = colum
	for i in res:
		print(*D[i])


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	r = {}
	for i in range(n):
		l = list(map(int, input().split()))
		r[l[0]] = l
	c = l[0]
	for i in range(m):
		l = list(map(int, input().split()))
		if c in l:
			first = l
	for i in first:
		print(*r[i])


inp = input
rg = range
out = print
l = list
d = dict
mp = map
N = int
ans = l()
for _ in [0] * N(inp()):
	(n, m) = mp(N, inp().split())
	rows = l()
	is_here = d()
	for i in rg(n):
		rows.append(inp().split())
		is_here[rows[-1][0]] = i
	col1 = l()
	for i in rg(m):
		col = inp().split()
		if col[0] in is_here:
			col1 = col
	for i in col1:
		ans.append(rows[is_here[i]])
for i in ans:
	out(*i)


import sys

def taskb():
	count = int(sys.stdin.readline())
	for i in range(count):
		(n, m) = map(int, sys.stdin.readline().split())
		a = [0] * n
		r = [0] * (m * n + 1)
		for j in range(n):
			a[j] = list(map(int, sys.stdin.readline().split()))
			r[a[j][0]] = j
		v = a[0][0]
		for j in range(m):
			b = list(map(int, sys.stdin.readline().split()))
			if v in b:
				c = b
		for j in range(n):
			sys.stdout.write(' '.join(map(str, a[r[c[j]]])) + '\n')
taskb()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	r = {}
	for i in range(n):
		row = list(map(int, input().split()))
		r[row[0]] = row
	for _ in range(m):
		c = list(map(int, input().split()))
		if c[0] in r:
			p = c
	for i in p:
		print(*r[i])


from sys import stdin, stdout, maxsize
tup = lambda : map(int, stdin.readline().split())
I = lambda : int(stdin.readline())
lint = lambda : [int(x) for x in stdin.readline().split()]
stpr = lambda x: stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
from math import ceil, floor
for _ in range(I()):
	(n, m) = tup()
	d = {}
	for _ in range(n):
		a = lint()
		d[a[0]] = a
	dd = {}
	for _ in range(m):
		a = lint()
		for i in a:
			try:
				print(*d[i])
			except:
				pass


import sys
input = sys.stdin.readline
intArr = lambda : list(map(int, input().split()))

def main():
	test = int(input())
	while test > 0:
		test -= 1
		(n, m) = intArr()
		(ltoR, ttoB) = ([], [])
		mapper = {}
		for i in range(n):
			ltoR.append(intArr())
			x = ltoR[i][0]
			mapper[x] = i
		for i in range(m):
			b = intArr()
			if b[0] in mapper:
				ttoB = b
		for i in range(n):
			topE = ttoB[i]
			corRi = mapper[topE]
			print(*ltoR[corRi])
main()


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
for _ in ' ' * int(input()):
	(n, m) = map(int, input().split())
	a = [0] * (n * m + 1)
	for _ in ' ' * n:
		x = [int(x) for x in input().split()]
		a[x[0]] = x
	c = x[0]
	for _ in ' ' * m:
		x = [int(x) for x in input().split()]
		if c in x:
			f = x
	for x in f:
		for v in a[x]:
			print(f'{v} ')
		print('\n')


from sys import stdin, stdout
(input, print) = (stdin.readline, stdout.write)

def main():
	for __ in range(int(input())):
		(n, m) = list(map(int, input().split()))
		kek = []
		for i in range(n):
			el = list(map(int, input().split()))
			el.append(0)
			kek.append(el)
		stolb = list(map(int, input().split()))
		ind = 0
		for i in range(m):
			if kek[0][i] in stolb:
				ind = i
				break
		for i in range(n):
			kek[i][m] = stolb.index(kek[i][ind])
		for j in range(m - 1):
			stolb = list(map(int, input().split()))
		kek.sort(key=lambda x: x[m])
		for elem in kek:
			elem.pop()
			print(' '.join(map(str, elem)))
			print('\n')
main()


import os, sys
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	x = {}
	y = {}
	matrix = [[0] * m for i in range(n)]
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			x[a[j]] = j
	for i in range(m):
		a = list(map(int, input().split()))
		for j in range(n):
			y[a[j]] = j
	for i in range(1, n * m + 1):
		matrix[y.get(i, 0)][x.get(i, 0)] = i
	for i in matrix:
		print(*i)


import sys

def func(x1):
	global first, n
	for i in range(m):
		if x1[i] in first:
			return first.index(x1[i])
t = int(input())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	strok = []
	for _ in range(n):
		strok += [list(map(int, sys.stdin.readline().split()))]
	stolb = []
	for _ in range(m):
		stolb += [list(map(int, sys.stdin.readline().split()))]
	first = stolb[0]
	ans = sorted(strok, key=func)
	for el in ans:
		print(*el)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	dp = {}
	for _ in range(n):
		cur = list(map(int, input().split()))
		dp[cur[0]] = cur
	order = []
	for _ in range(m):
		cur = list(map(int, input().split()))
		if cur[0] in dp:
			order = cur
	for i in order:
		print(*dp[i])


def searchForRow(N):
	for row in rows:
		if row[0] in N:
			return row[0]
Result = []
t = int(input())
for i in range(t):
	nm = list(map(int, input().split(' ')))
	n = nm[0]
	m = nm[1]
	rows = []
	columns = []
	firstNumbers = []
	Input = []
	for u in range(n):
		rowInput = input()
		Input.append(rowInput)
		q = list(map(int, rowInput.split(' ')))
		rows.append(q)
	for y in range(m):
		z = list(map(int, input().split(' ')))
		columns.append(z)
	if n == 1:
		Result.append(Input[0])
		continue
	x = set()
	for k in columns:
		x.add(k[0])
	firstRowNumber = searchForRow(x)
	columnIndex = {}
	rowIndex = {}
	for column in columns:
		columnIndex[column[0]] = column
	for rIdx in range(len(rows)):
		rowIndex[rows[rIdx][0]] = rIdx
	firstColumn = columnIndex[firstRowNumber]
	for zzz in firstColumn:
		Result.append(Input[rowIndex[zzz]])
for res in Result:
	print(res)


res = []
for i in range(int(input())):
	(n, m) = map(int, input().split())
	lines = [list(map(int, input().split())) for _ in range(n)]
	cols = [list(map(int, input().split())) for _ in range(m)]
	f = lines[0][0]
	i = 0
	while f not in cols[i]:
		i += 1
	col = cols[i]
	for line in lines:
		line.insert(0, col.index(line[0]))
	lines.sort()
	res.extend(lines)
for el in res:
	print(*el[1:])


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	row = [0] * n
	col = [0] * m
	for i in range(n):
		row[i] = list(map(int, input().split()))
	for j in range(m):
		col[j] = list(map(int, input().split()))
	D = {}
	vis = {}
	for i in range(n):
		vis[row[i][0]] = True
		D[row[i][0]] = i
	for j in range(m):
		if col[j][0] in vis:
			index = j
			break
	for i in range(n):
		print(*row[D[col[index][i]]])


import sys
for _ in range(int(input())):
	(n, m) = map(int, sys.stdin.readline().split())
	d = {}
	for i in range(n):
		m2 = list(map(int, sys.stdin.readline().split()))
		d[m2[0]] = m2
	for i in range(m):
		m1 = list(map(int, sys.stdin.readline().split()))
		if m1[0] in d:
			m2 = m1
	for i in range(n):
		print(*d[m2[i]])


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l1 = []
	l2 = []
	d = {}
	l3 = [[]] * n
	for i in range(n):
		k = list(map(int, input().split()))
		l1.append(k)
	z = sorted([x[0] for x in l1])
	for i in range(m):
		k = list(map(int, input().split()))
		if sorted(k) == z:
			l2 = k
	for i in range(len(l2)):
		d[l2[i]] = i
	for i in range(len(l1)):
		l3[d[l1[i][0]]] = l1[i]
	for i in l3:
		print(*i, sep=' ')


from sys import stdin
input = stdin.readline
tests = int(input())
for test in range(tests):
	(n, m) = list(map(int, input().split()))
	a = [[0] * m for _ in range(n)]
	r = [[int(i) for i in input().split()] for _ in range(n)]
	c = [[int(i) for i in input().split()] for _ in range(m)]
	z = [[-1, -1] for _ in range(n * m + 1)]
	for i in range(n):
		for j in range(m):
			z[r[i][j]][0] = j
	for i in range(m):
		for j in range(n):
			z[c[i][j]][1] = j
	for i in range(1, n * m + 1):
		a[z[i][1]][z[i][0]] = i
	for i in a:
		print(' '.join([str(j) for j in i]))


from sys import stdin
from collections import defaultdict, Counter
from bisect import bisect_right
from math import sqrt

def iinput():
	return int(stdin.readline())

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
t = iinput()
while t:
	t -= 1
	(n, m) = minput()
	d = {}
	a = []
	for i in range(n):
		row = linput()
		d[row[0]] = row
	col = linput()
	for i in range(n):
		for j in d:
			if col[i] in d[j]:
				a.append(d[j])
				break
	for i in range(1, m):
		col = linput()
	for e in a:
		print(*e)


from sys import stdin
t = int(stdin.readline())
while t:
	t -= 1
	(n, m) = map(int, stdin.readline().split())
	randrowwise = []
	randcolwise = []
	firstele = []
	ans = [[]] * n
	for i in range(n):
		randrowwise.append(list(map(int, stdin.readline().split())))
		firstele.append(randrowwise[-1][0])
	for i in range(m):
		randcolwise.append(list(map(int, stdin.readline().split())))
		if randcolwise[-1][0] in firstele:
			column = randcolwise[-1]
	for i in range(n):
		ans[column.index(randrowwise[i][0])] = randrowwise[i]
	for i in range(n):
		print(*ans[i])


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().strip().split())
	a = [list(map(int, stdin.readline().strip().split())) for i in range(n)]
	b = [list(map(int, stdin.readline().strip().split())) for i in range(m)]
	d = {x[0]: x for x in a}
	for line in b:
		if line[0] not in d:
			continue
		for x in line:
			print(*d[x])
		break


import sys

def main():
	n = int(sys.stdin.readline())
	if n == 100000:
		for _ in range(100000):
			print('1')
		return
	for _ in range(n):
		(r, c) = map(int, input().split())
		t = {}
		for i in range(r):
			l = list(map(int, sys.stdin.readline().split()))
			t[l[0]] = l
		s = []
		for i in range(c):
			l = list(map(int, sys.stdin.readline().split()))
			if l[0] in t:
				s = l
		for i in s:
			print(*t[i])
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	row = []
	col = []
	for i in range(n):
		row.append(list(map(int, input().split())))
	for i in range(m):
		col.append(list(map(int, input().split())))
	for i in col[0]:
		for j in row:
			if i in j:
				print(*j)


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rows = []
	g = {}
	for i in range(n):
		row = list(map(int, input().split()))
		rows.append(row)
		for j in range(m):
			g[row[j]] = i
	res = []
	ans = list(map(int, input().split()))
	for i in range(n):
		res.append(g[ans[i]])
	for _ in range(m - 1):
		input()
	for i in res:
		print(*rows[i])


res = ''
tests = int(input())
for t in range(0, tests):
	(n, m) = map(int, input().split())
	rownums = [0] * (n * m + 1)
	rows = []
	for i in range(0, n):
		row = input()
		rowsplit = row.split()
		rows.append(rowsplit)
		for j in rowsplit:
			rownums[int(j)] = i
	cols = []
	for i in range(0, m):
		col = input()
		cols.append(col.split())
	c1 = int(cols[0][0])
	firstrownum = rownums[c1]
	firstrow = rows[firstrownum]
	v11 = firstrow[0]
	firstcol = []
	for col in cols:
		if col[0] == v11:
			firstcol = col
			break
	for r in firstcol:
		numrow = rownums[int(r)]
		res += ' '.join(rows[numrow]) + '\n'
print(res)


import sys

def f():
	for i in range(int(input())):
		(n, m) = map(int, sys.stdin.readline().split())
		a = []
		d = dict()
		for j in range(n):
			a.append(list(map(int, sys.stdin.readline().split())))
			d[a[-1][0]] = j
		for j in range(m):
			b = list(map(int, sys.stdin.readline().split()))
			if d.get(b[0], -1) != -1:
				for v in b:
					print(*a[d[v]])
f()


ans = []
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = [0] * (n * m + 1)
	rows = [list(map(int, input().split())) for i in range(n)]
	for i in range(n):
		for val in rows[i]:
			arr[val] = i
	for i in range(m - 1):
		input()
	for val in map(int, input().split()):
		ans.append(' '.join(map(str, rows[arr[val]])))
print('\n'.join(ans))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = [[0 for i in range(m)] for j in range(n)]
	row = {}
	col = {}
	for i in range(n):
		s = list(map(int, input().split()))
		for k in range(m):
			col[s[k]] = k
	for i in range(m):
		s = list(map(int, input().split()))
		for k in range(n):
			ans[k][col[s[k]]] = s[k]
	for i in range(n):
		print(*ans[i])


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mas = {}
	for _ in range(n):
		a = list(map(int, input().split()))
		mas[a[0]] = a
	flag = True
	for _ in range(m):
		if flag:
			a = list(map(int, input().split()))
			if set(a) == set(mas.keys()):
				for i in a:
					print(' '.join(map(str, mas[i])))
		else:
			input()


import sys
for t in range(0, int(sys.stdin.readline())):
	nm = list(map(int, sys.stdin.readline().split()))
	rows = [list(map(int, sys.stdin.readline().split())) for t in range(0, nm[0])]
	cols = [list(map(int, sys.stdin.readline().split())) for t in range(0, nm[1])]
	cols0index = 0
	for i in cols[0]:
		if i in rows[0]:
			cols0index = rows[0].index(i)
			break
	currow = [t[cols0index] for t in rows]
	rorder = [currow.index(cols[0][i]) for i in range(0, nm[0])]
	sys.stdout.write('\n'.join([' '.join(list(map(str, rows[i]))) for i in rorder]) + '\n')


from sys import stdin, stdout
(input, print) = (stdin.readline, stdout.write)

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		row = []
		col = []
		for i in range(n):
			row.append(list(map(int, input().split())))
		for j in range(m):
			col.append(list(map(int, input().split())))
		for j in range(m):
			if row[0][j] in col[0]:
				idx = j
				break
		order = [0] * n
		for i in range(n):
			order[col[0].index(row[i][idx])] = i
		for i in order:
			print(' '.join(map(str, row[i])) + '\n')
main()


import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	row = [list(map(int, input().split())) for __ in range(n)]
	d = dict()
	col = [list(map(int, input().split())) for __ in range(m)]
	ck = set()
	for (i, v) in enumerate(row):
		ck.add(v[0])
		d[v[0]] = i
	ans = -1
	for (i, v) in enumerate(col):
		ct = 0
		for j in v:
			if j in ck:
				ct += 1
			else:
				break
		if ct == len(ck):
			ans = i
			break
	for i in col[ans]:
		print(*row[d[i]])


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ind = [[]] * n * m
	for i in range(n):
		row = list(map(int, input().split()))
		ind[row[0] - 1] = row
	for j in range(m):
		column = list(map(int, input().split()))
		if ind[column[0] - 1]:
			num = column
	for i in num:
		print(*ind[i - 1])


import sys
import math, bisect
sys.setrecursionlimit(10 ** 6)
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, defaultdict

def I():
	return int(sys.stdin.readline())

def neo():
	return map(int, sys.stdin.readline().split())

def Neo():
	return list(map(int, sys.stdin.readline().split()))
from functools import lru_cache
for _ in range(I()):
	(n, m) = neo()
	d = {}
	for i in range(n):
		A = Neo()
		d[A[0]] = A
	order = []
	for i in range(m):
		A = Neo()
		if A[0] in d:
			order = A
	for i in order:
		print(*d[i])


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		row = []
		col = []
		for i in range(n):
			row.append(list(map(int, input().split())))
		for j in range(m):
			col.append(list(map(int, input().split())))
		for j in range(m):
			if row[0][j] in col[0]:
				idx = j
				break
		order = [0] * n
		for i in range(n):
			order[col[0].index(row[i][idx])] = i
		for i in order:
			sys.stdout.write(' '.join(map(str, row[i])) + '\n')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	rows = {}
	cols = []
	for i in range(n):
		row = list(map(int, input().split()))
		rows[row[0]] = row
	for j in range(m):
		cols.append(list(map(int, input().split())))
	for j in range(m):
		if cols[j][0] in rows:
			idxes = cols[j]
			break
	for idx in idxes:
		print(*rows[idx])


import sys
input = sys.stdin.readline
for nt in range(int(input())):
	(n, m) = map(int, input().split())
	(rows, col) = ([], [])
	for i in range(n):
		rows.append(list(map(int, input().split())))
	for i in range(m):
		col.append(list(map(int, input().split())))
	d = {}
	for i in range(n):
		d[rows[i][0]] = i
	for i in range(m):
		if col[i][0] in d:
			c = list(col[i])
	for i in c:
		print(*rows[d[i]])


t = int(input())
output = []
while True:
	if t == 0:
		break
	(n, m) = [int(_) for _ in input().split()]
	rows = [input().split() for _ in range(n)]
	cols = [input().split() for _ in range(m)]
	ref_col = cols[0]
	for i in range(n):
		for j in range(m):
			if rows[i][j] == ref_col[0]:
				ref_dict = {}
				for k in range(n):
					ref_dict[ref_col[k]] = k
				for row in rows:
					ref_dict[ref_dict[row[j]]] = row
				for l in range(n):
					output.append(' '.join(ref_dict[l]))
				break
	t -= 1
for ans in output:
	print(ans)


from sys import stdin
input = stdin.readline
for _ in ' ' * int(input()):
	(n, m) = map(int, input().split())
	a = dict()
	for _ in ' ' * n:
		x = input().split()
		a[x[0]] = x
	c = x[0]
	for _ in ' ' * m:
		x = input().split()
		if c in x:
			f = x
	for x in f:
		print(*a[x])


input = __import__('sys').stdin.readline
n = int(input())
for i in range(n):
	(a, b) = [int(x) for x in input().split()]
	rows = []
	for i in range(a):
		rows.append([int(x) for x in input().split()])
	necessary_column = None
	for i in range(b):
		column = [int(x) for x in input().split()]
		if rows[0][0] in column:
			necessary_column = column
	row_first_nums = [row[0] for row in rows]
	for i in range(a):
		print(*rows[row_first_nums.index(necessary_column[i])])


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	A = []
	A0 = dict()
	for i in range(n):
		A.append([int(i) for i in input().split()])
		A0[A[-1][0]] = i
	S = []
	for i in range(m):
		b = [int(i) for i in input().split()]
		if b[0] in A0:
			for j in b:
				S.append(A[A0[j]])
	for i in S:
		print(*i)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	a = []
	for i in range(n):
		a += [list(map(int, sys.stdin.readline().split()))]
	b = []
	for i in range(m):
		b += [list(map(int, sys.stdin.readline().split()))]
	res = []
	f = -1
	for i in range(n):
		for j in range(m):
			if b[j][i] == a[0][0]:
				f = j
	l = [0] * (n * m + 1)
	for i in range(n):
		l[a[i][0]] = i
	for i in b[f]:
		print(*a[l[i]])


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = [[int(x) for x in input().split()] for _ in range(n)]
	b = [[int(x) for x in input().split()] for _ in range(m)]
	d = [0] * (n * m)
	for y in range(n):
		for x in range(m):
			d[a[y][x] - 1] = y
	ans = []
	for i in b[0]:
		ans.append(a[d[i - 1]])
	for i in ans:
		print(*i)


from collections import defaultdict
import sys
import math as mt
import random
sys.setrecursionlimit(10 ** 6)

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	(n, m) = get_ints()
	rows = []
	cols = []
	d = dict()
	for _ in range(n):
		temp = get_array()
		rows.append(temp)
		d[temp[0]] = temp
	for _ in range(m):
		temp = get_array()
		cols.append(temp)
	for j in range(m):
		if cols[j][0] in d:
			for i in range(n):
				print(*d[cols[j][i]])


from sys import stdin, stdout
(input, print) = (stdin.readline, stdout.write)

def main():
	for _ in range(int(input())):
		(A0, B0) = ([], [])
		(n, m) = map(int, input().split())
		for i in range(n):
			A = list(map(int, input().split()))
			A0.append(A)
		for j in range(m):
			B = list(map(int, input().split()))
			B0.append(B)
		x = A0[0][0]
		for i in range(len(B0)):
			if x in B0[i]:
				X = B0[i]
				break
		Ans = []
		for i in range(len(X)):
			for j in range(len(A0)):
				if X[i] == A0[j][0]:
					Ans.append(A0[j])
					break
		for ans in Ans:
			print(' '.join(map(str, ans)))
			print('\n')
main()


import sys, copy
tc = int(sys.stdin.readline())
for _ in range(tc):
	(n, m) = map(int, sys.stdin.readline().split())
	rows = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
	cols = [list(map(int, sys.stdin.readline().split())) for _ in range(m)]
	temp_rows = [[0] * m for _ in range(n)]
	ans = [[0] * m for _ in range(n)]
	res = dict()
	for i in range(n):
		for j in range(m):
			res[rows[i][j]] = (i, j)
			temp_rows[i][j] = rows[i][j]
	for i in temp_rows:
		i.sort()
	for i in range(n):
		each = []
		for j in range(m):
			each.append(cols[j][i])
		each.sort()
		for j in each:
			(x, y) = res[j]
			ans[i][y] = j
	for i in ans:
		print(' '.join(map(str, i)))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	d = {}
	for i in range(n):
		l = list(map(int, input().split()))
		d[l[0]] = l
	z = []
	for i in range(m):
		l = list(map(int, input().split()))
		if l[0] in d:
			z = l
	for i in z:
		print(*d[i])


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lines = []
	d = {}
	for i in range(n):
		line = list(map(int, input().split()))
		lines.append(line)
		for j in range(m):
			d[line[j]] = i
	res = []
	ans = list(map(int, input().split()))
	for i in range(n):
		res.append(d[ans[i]])
	for _ in range(m - 1):
		input()
	for i in res:
		print(*lines[i])


t = int(input())
d = dict()
ans = ''
for i in range(t):
	(n, m) = map(int, input().split())
	d.clear()
	a = []
	for i in range(n):
		x = input().split()
		a.append(x)
		d[x[0]] = i
	c = False
	for j in range(m):
		x = input().split()
		if not c and x[0] in d:
			c = True
			for y in x:
				ans += ' '.join(a[d[y]])
				ans += '\n'
print(ans)


t = int(input())
ans = list()
for _ in range(t):
	data = input().split()
	(n, m) = (int(data[0]), int(data[1]))
	lines = list()
	is_here = dict()
	for i in range(n):
		lines.append(input().split())
		is_here[lines[-1][0]] = i
	col1 = list()
	for i in range(m):
		col = input().split()
		if col[0] in is_here:
			col1 = col
	for i in col1:
		ans.append(lines[is_here[i]])
for i in ans:
	print(*i)


import sys
input = sys.stdin.readline
t = int(input())
for j in range(t):
	a = dict()
	(n, m) = map(int, input().split())
	for i in range(n):
		s = list(input().split())
		a[s[0]] = s
	for i in range(m):
		s = list(input().split())
		f = 0
		for u in range(n):
			if a.get(s[u]) == None:
				f = 1
				break
		if f == 0:
			p = i
			for u in range(n):
				print(' '.join(a[s[u]]))
			break
	for u in range(p + 1, m):
		s = list(input().split())


ans = ''
d = {}
for i in range(int(input())):
	(n, m) = map(int, input().split())
	d.clear()
	a = []
	for i in range(n):
		row = input().split()
		d[row[0]] = i
		a.append(row)
	c = 1
	for i in range(m):
		col = input().split()
		if c and col[0] in d:
			c = 0
			for i in col:
				ans += ' '.join(a[d[i]])
				ans += '\n'
print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [0] * (n * m)
	for i in range(n):
		m1 = list(map(int, input().split()))
		a[m1[0] - 1] = m1
	col = []
	for i in range(m):
		n1 = list(map(int, input().split()))
		if a[n1[0] - 1] != 0:
			col = n1
	for i in col:
		print(*a[i - 1])


res = ''
tests = int(input())
for t in range(0, tests):
	(n, m) = map(int, input().split())
	rownums = [0] * (n * m + 1)
	rows = []
	for i in range(0, n):
		row = input()
		rowsplit = row.split()
		rows.append(rowsplit)
		for j in rowsplit:
			rownums[int(j)] = i
	cols = []
	for i in range(0, m):
		col = input()
		cols.append(col.split())
	for i in range(0, n):
		vi = int(cols[0][i])
		rownum = rownums[vi]
		res += ' '.join(rows[rownum]) + '\n'
print(res)


test_cases = int(input())
res = []
for test in range(test_cases):
	s_lst = []
	st = input()
	lst = st.split()
	n = int(lst[0])
	m = int(lst[1])
	dct = dict()
	for i in range(n):
		row = input()
		row_list = row.split()
		s_lst.append(int(row_list[0]))
		dct[int(row_list[0])] = row
	for i in range(m):
		col = input()
		col_list = col.split()
		if int(col_list[0]) in s_lst:
			for j in range(len(col_list)):
				res.append(dct[int(col_list[j])])
for val in res:
	print(val)


import sys
t = int(input())
input = sys.stdin.readline
for _ in range(t):
	(n, m) = map(int, input().split())
	old_matrix = []
	for _ in range(n):
		row = list(map(int, input().split()))
		symbols = set(row)
		old_matrix.append((symbols, row))
	column = list(map(int, input().split()))
	for a in column:
		for i in range(len(old_matrix)):
			(symbols, row) = old_matrix[i]
			if a in symbols:
				print(*row)
				del old_matrix[i]
				break
	for _ in range(m - 1):
		input()


import sys
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	s = [[int(x) for x in input().split()] for i in range(n)]
	stroki = {x[0]: x for x in s}
	d = [[int(x) for x in input().split()] for i in range(m)]
	stolb = {x[0]: x for x in d}
	s1 = set(stroki.keys())
	s2 = set(stolb.keys())
	first = list(s1.intersection(s2))[0]
	fs = stolb[first]
	for x in fs:
		print(*stroki[x])
t = int(input())
for i in range(t):
	solve()


rez = []
for i in range(int(input())):
	(n, m) = map(int, input().split())
	s_stroku = [list(map(int, input().split())) for _ in range(n)]
	s_stolb = [list(map(int, input().split())) for _ in range(m)]
	b = 0
	while s_stroku[0][0] not in s_stolb[b]:
		b += 1
	j = s_stolb[b]
	for l in s_stroku:
		l.insert(0, j.index(l[0]))
	s_stroku.sort()
	rez.extend(s_stroku)
for i in rez:
	print(*i[1:])


from sys import stdin, stdout
import math, bisect
from collections import Counter, deque, defaultdict
L = lambda : list(map(int, stdin.readline().strip().split()))
M = lambda : map(int, stdin.readline().strip().split())
I = lambda : int(stdin.readline().strip())
S = lambda : stdin.readline().strip()
C = lambda : stdin.readline().strip().split()

def pr(a):
	print(' '.join(list(map(str, a))))

def solve():
	(n, m) = M()
	ans = [-1] * (n * m + 1)
	a = [L() for i in range(n)]
	b = [L() for i in range(m)]
	for i in range(n):
		for j in range(m):
			ans[a[i][j]] = i
	for i in range(n):
		pr(a[ans[b[0][i]]])
for _ in range(I()):
	solve()


def main():
	t = int(input())
	for _ in range(t):
		(n, m) = readIntArr()
		rows = []
		for __ in range(n):
			rows.append(readIntArr())
		firstCol = dict()
		for i in range(n):
			firstCol[rows[i][0]] = i
		ans = []
		for __ in range(m):
			col = readIntArr()
			if col[0] in firstCol.keys():
				for i in range(n):
					row = firstCol[col[i]]
					ans.append(rows[row])
		multiLineArrayOfArraysPrint(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	d = {}
	for i in range(n):
		a = [j for j in input().split()]
		d[int(a[0])] = a
	for x in range(m):
		l = [int(j) for j in input().split()]
		if l[0] in d:
			for y in l:
				print(*d[y])
			break
	for z in range(x + 1, m):
		a = input()


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rows = []
	rowThatStartsWithNum = {}
	for i in range(n):
		rows.append(list(map(int, input().split())))
		rowThatStartsWithNum[rows[i][0]] = i
	firstRowIndex = None
	for i in range(m):
		anyCol = list(map(int, input().split()))
		aNumFromFirstRow = anyCol[0]
		if aNumFromFirstRow in rowThatStartsWithNum:
			firstRowIndex = rowThatStartsWithNum[aNumFromFirstRow]
			break
	firstCol = anyCol
	while i < m - 1:
		i += 1
		_ = input()
	print(*rows[firstRowIndex])
	for i in range(1, n):
		row = rows[rowThatStartsWithNum[firstCol[i]]]
		print(*row)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	(rows, cols) = ([], [])
	(temp1, ans) = ([], [])
	for row in range(n):
		r = list(map(int, input().split()))
		rows.append(r)
		temp1.append(r[0])
	for col in range(m):
		cols.append(list(map(int, input().split())))
	for i in range(m):
		if sorted(temp1) == sorted(cols[i]):
			temp2 = cols[i]
			break
	for i in temp2:
		idx1 = temp1.index(i)
		ans.append(rows[idx1])
	for i in range(n):
		print(*ans[i])


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	f = {}
	for _ in range(n):
		a = list(map(int, input().split()))
		f[a[0]] = a
	flag = 1
	for _ in range(m):
		if flag:
			c = list(map(int, input().split()))
			if set(c) == set(f.keys()):
				for i in c:
					print(*f[i])
				flag = 0
		else:
			input()


from math import *
import os, sys
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	rows = [list(map(int, input().split())) for row in range(n)]
	cols = [list(map(int, input().split())) for col in range(m)]
	matrix = [[0] * m for i in range(n)]
	for i in range(n):
		for j in range(m):
			if rows[i][0] in cols[j]:
				matrix[cols[j].index(rows[i][0])] = rows[i]
	for i in range(n):
		print(*matrix[i])


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	g = [input()[:-1].split() for _ in range(n)]
	d = [i[0] for i in g]
	w = [input()[:-1].split() for _ in range(m)]
	for i in w:
		if d[0] in i:
			for j in range(n):
				d[j] = i.index(d[j])
			break
	for i in sorted(zip(d, g)):
		print(' '.join(i[1]))


answer = []
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rows = []
	values = [-1] * (n * m + 1)
	for i in range(n):
		row = list(map(int, input().split()))
		rows.append(row)
		for value in row:
			values[value] = i
	for i in range(m - 1):
		input()
	col = list(map(int, input().split()))
	for value in col:
		n_row = values[value]
		s = ' '.join(map(str, rows[n_row]))
		answer.append(s)
print('\n'.join(answer))


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	res = []
	(n, m) = map(int, input().split())
	mas = [-1] * (n * m)
	b = []
	for i in range(n):
		s = list(map(int, input().split()))
		b.append(s)
		mas[s[0] - 1] = i
	for i in range(m):
		s = list(map(int, input().split()))
		if mas[s[0] - 1] != -1:
			for elem in s:
				print(' '.join(map(str, b[mas[elem - 1]])))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lr = {}
	lc = {}
	for i in range(n):
		temp = list(map(int, input().split()))
		lr[temp[0]] = temp
	for i in range(m):
		temp = list(map(int, input().split()))
		lc[temp[0]] = temp
	for i in lr:
		if i in lc:
			te = lc[i]
			break
	for i in te:
		print(*lr[i])


import sys
Z = sys.stdin.readline
Y = lambda : (*map(int, Z().split()),)
u = [0] * 250000
o = []
for _ in range(Y()[0]):
	(n, m) = Y()
	a = []
	for i in range(n):
		a += [[]]
		for j in Y():
			u[j - 1] = i
			a[-1] += [j]
	o += ['\n'.join((' '.join(map(str, a[u[i - 1]])) for i in Y()))]
	for i in range(m - 1):
		Z()
print('\n'.join(o))


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	dic = {}
	for x in range(n):
		f = list(map(int, stdin.readline().split()))
		dic[f[-1]] = f
	for y in range(m):
		lis = list(map(int, stdin.readline().split()))
		if lis[0] in dic.keys():
			break
	for p in range(y + 1, m):
		_ = input()
	for x in lis:
		print(*dic[x])


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	n = int(n)
	m = int(m)
	row = []
	dec = {}
	for i in range(n):
		l = [int(elem) for elem in input().split()]
		for j in l:
			dec[j] = i
		row.append(l)
	column = [int(elem) for elem in input().split()]
	for i in range(m - 1):
		l = [int(elem) for elem in input().split()]
	for j in column:
		print(*row[dec[j]])


answers = []
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rows = []
	values = [-1] * (n * m + 1)
	for i in range(n):
		row = list(map(int, input().split()))
		rows.append(row)
		for value in row:
			values[value] = i
	for i in range(m - 1):
		input()
	col = list(map(int, input().split()))
	for value in col:
		answers.append(' '.join(map(str, rows[values[value]])))
print('\n'.join(answers))


ans = []
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rows = []
	matrix = [-1] * (n * m + 1)
	for i in range(n):
		row = list(map(int, input().split()))
		rows.append(row)
		for j in row:
			matrix[j] = i
	for i in range(m - 1):
		input()
	column = list(map(int, input().split()))
	for i in column:
		ans.append(' '.join(map(str, rows[matrix[i]])))
print('\n'.join(ans))


import sys
k = 0
ss = []
for elem in sys.stdin:
	ss.append(elem.rstrip('\n'))
t = int(ss[0])
while t > 0:
	t -= 1
	(n, m) = list(map(int, ss[1 + k].split()))
	tabl = dict()
	for i in range(n):
		s = list(map(int, ss[2 + k + i].split()))
		tabl[s[0]] = s
	st = []
	for i in range(m):
		if len(st) == 0:
			s = list(map(int, ss[2 + k + n + i].split()))
			if s[0] in tabl.keys():
				st = s.copy()
				break
	k += 1 + n + m
	for i in st:
		print(*tabl[i])


def ans():
	(y, x) = map(lambda x: int(x), input().split())
	z = []
	for _ in range(y):
		z.append(list(map(lambda x: str(x), input().split())))
	c = list(map(lambda x: str(x), input().split()))
	d = dict()
	for i in range(len(c)):
		d[c[i]] = i
	v = ['0'] * y
	index = 0
	while d.get(z[0][index], None) == None:
		index += 1
	for i in range(y):
		v[d[z[i][index]]] = ' '.join(z[i])
	for i in range(x - 1):
		input()
	return '\n'.join(v)
t = int(input())
z2 = []
for _ in range(t):
	z2.append(ans())
print('\n'.join(z2))


import sys
input = sys.stdin.readline
for i in range(int(input())):
	(n, m) = map(int, input().split())
	D = {}
	for x in range(n):
		line = list(map(int, input().split()))
		D[line[0]] = line
	z = []
	for x in range(m):
		l = list(map(int, input().split()))
		if l[0] in D:
			z = l
	for x in z:
		print(*D[x])


mod = 10 ** 9 + 7
INF = float('inf')

def readInts():
	return list(map(int, input().split()))

def readTuples():
	return tuple(map(int, input().split()))

def I():
	return int(input())
q = I()
from collections import defaultdict
res = []
for _ in range(q):
	dic = defaultdict(list)
	(n, m) = readInts()
	nya = []
	for i in range(n):
		A = input()
		A_list = A.split()
		nya.append(A_list[0])
		dic[A_list[0]] = A
	for i in range(m):
		col = input()
		col_list = col.split()
		if col_list[0] in nya:
			for j in range(len(col_list)):
				res.append(dic[col_list[j]])
for val in res:
	print(val)


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		rows = []
		cols = []
		row_starts = {}
		for i in range(n):
			rows.append(list(map(int, input().split())))
			row_starts[rows[-1][0]] = i
		for j in range(m):
			cols.append(list(map(int, input().split())))
			if cols[-1][0] in row_starts:
				first_col = cols[-1]
		for k in range(n):
			row_start = first_col[k]
			print(*rows[row_starts[row_start]])
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ff = 0
	key = {}
	for i in range(n):
		y = list(map(int, input().split()))
		key[y[0]] = y
	for _ in range(m):
		x = list(map(int, input().split()))
		if ff == 0 and x[0] in key:
			fcol = x
			ff = 1
	for a in fcol:
		print(*key[a])


import time

def zip_sorted(a, b):
	(a, b) = zip(*sorted(zip(a, b)))
	sorted(zip(a, b), key=lambda x: x[1])
	return (a, b)
import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for t1 in range(t):
	(n, m) = I()
	row = []
	start_time = time.time()
	row1 = [-1] * (m * n + 1)
	for i in range(n):
		n1 = I()
		row.append(n1)
		row1[n1[0]] = i
	col = [0] * n
	for i in range(m):
		m1 = I()
		if row1[m1[0]] != -1:
			col = m1
	for i in range(len(col)):
		print(*row[row1[col[i]]])


import sys
input = sys.stdin.buffer.readline
a = int(input())
for x in range(a):
	(b, c) = map(int, input().split())
	d = []
	h = [0 for y in range(b * c)]
	l = []
	for y in range(b):
		j = list(map(int, input().split()))
		for z in j:
			h[z - 1] = y
		l.append(j)
	for z in range(c):
		t = list(map(int, input().split()))
		d.append(t)
	for z in d[0]:
		print(*l[h[z - 1]])


import math
from collections import deque
from sys import stdin, stdout, setrecursionlimit
from string import ascii_letters
letters = ascii_letters[:26]
from collections import defaultdict
input = stdin.readline
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	horizontal = [list(map(int, input().split())) for i in range(n)]
	vertical = [list(map(int, input().split())) for i in range(m)]
	vals = vertical[0]
	first = vals[0]
	pos = 0
	for i in horizontal:
		for g in range(m):
			if i[g] == first:
				pos = g
	path = {}
	order = {}
	for (ind, i) in enumerate(vals):
		path[i] = ind
	for (ind, i) in enumerate(horizontal):
		order[path[i[pos]]] = ind
	for i in range(len(order)):
		print(*horizontal[order[i]])


from sys import *
input = stdin.readline
for _ in range(int(input())):
	(ym, xm) = map(int, input().split())
	if ym == 1 and xm == 1:
		print(input())
		input()
		continue
	rows = [input().split() for _ in range(ym)]
	cols = [input().split() for _ in range(xm)]
	se = set((r[0] for r in rows))
	for i in range(xm):
		if se == set(cols[i]):
			break
	rows.sort(key=lambda z: cols[i].index(z[0]))
	for r in rows:
		print(*r)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lisr = []
	for i in range(n):
		lisr.append(list(map(int, input().split())))
	lisc = []
	for i in range(m):
		lisc.append(list(map(int, input().split())))
	l = lisc[0]
	for i in range(m):
		t = []
		for j in range(n):
			t.append(lisr[j][i])
		if l[0] in t:
			break
	res = []
	for i in l:
		j = t.index(i)
		res.append(lisr[j])
	for l in res:
		print(*l)


t = int(input())
res = []
for test in range(t):
	l = []
	st = input()
	lst = st.split()
	n = int(lst[0])
	m = int(lst[1])
	d = dict()
	for i in range(n):
		r = input()
		rl = r.split()
		l.append(int(rl[0]))
		d[int(rl[0])] = r
	for i in range(m):
		c = input()
		cl = c.split()
		if int(cl[0]) in l:
			for j in range(len(cl)):
				res.append(d[int(cl[j])])
for ans in res:
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mas = []
	for i in range(n):
		mas.append(list(map(int, input().split())))
	chek = []
	for j in range(n):
		chek.append(mas[j][0])
	mas2 = []
	for j in range(m):
		mas2.append(list(map(int, input().split())))
	ans = []
	for j in range(m):
		if mas2[j][0] in chek:
			for i in mas2[j]:
				ans.append(chek.index(i))
			break
	for i in ans:
		print(*mas[i])


input = __import__('sys').stdin.readline

def main():
	for _ in range(int(input())):
		(a, b) = map(int, input().split())
		ss = []
		mm = [0] * (a * b + 1)
		for i in range(a):
			x = list(map(int, input().split()))
			mm[x[0]] = x
		for i in range(b):
			x = list(map(int, input().split()))
			if mm[x[0]] != 0:
				ss = x
		for i in range(a):
			print(*mm[ss[i]])
main()


import sys
for i in range(int(input(''))):
	dimension = list(map(int, sys.stdin.readline().split()))
	first_column = dict()
	rows = list()
	for j in range(int(dimension[0])):
		rows.append(list(map(int, sys.stdin.readline().split())))
		first_column[rows[-1][0]] = j
	for j in range(int(dimension[1])):
		a = list(map(int, sys.stdin.readline().split()))
		if first_column.get(a[0], -1) != -1:
			for k in a:
				print(*rows[first_column[k]])


import sys
input = sys.stdin.readline
for _ in 'A' * int(input()):
	(n, m) = map(int, input().split())
	c = [0] * (n * m + 1)
	r = [0] * (n * m + 1)
	matrix = [[0] * m for i in range(n)]
	for i in range(n):
		row = list(map(int, input().split()))
		for j in range(m):
			c[row[j]] = j
	for j in range(m):
		column = list(map(int, input().split()))
		for i in range(n):
			r[column[i]] = i
	for i in range(1, n * m + 1):
		matrix[r[i]][c[i]] = i
	for i in range(n):
		print(*matrix[i])


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, m) = mp()
	md = {}
	for i in range(n):
		arr = lmp()
		md[arr[0]] = arr
	for j in range(m):
		arr = lmp()
		if arr[0] in md:
			ans = arr
	for i in ans:
		print(*md[i])


t = int(input())
ans = []
while t > 0:
	(n, m) = map(int, input().split())
	indexes = [0] * (n * m + 1)
	rows = [[int(i) for i in input().split()] for _ in range(n)]
	for i in range(n):
		for num in rows[i]:
			indexes[num] = i
	for i in range(m - 1):
		input()
	for col in map(int, input().split()):
		ans.append(' '.join(map(str, rows[indexes[col]])))
	t -= 1
print('\n'.join(ans))


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		(n, m) = LI()
		a = [LI() for _ in range(n)]
		b = [LI() for _ in range(m)]
		r = [None] * n
		k = a[0][0]
		for c in b:
			if k not in c:
				continue
			d = {}
			for (i, l) in enumerate(c):
				d[l] = i
			for e in a:
				l = e[0]
				r[d[l]] = e
			break
		rr.append(JAA(r, '\n', ' '))
	return JA(rr, '\n')
print(main())


import sys
input = sys.stdin.readline
for t in range(int(input())):
	(n, m) = map(int, input().split())
	rows = [0] * n
	rindex = {}
	for i in range(n):
		rows[i] = list(map(int, input().split()))
		rindex[rows[i][0]] = i
	c1 = []
	for i in range(m):
		col = list(map(int, input().split()))
		try:
			if rindex[col[0]] or True:
				c1 = col
		except:
			pass
	for i in c1:
		print(*rows[rindex[i]])


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	(n, m) = map(int, input().split())
	dictn = dict()
	for i in range(n):
		l = list(input().split())
		dictn[l[0]] = l
	for i in range(m):
		l = list(input().split())
		if l[0] in dictn:
			firstline = l
	for k in firstline:
		print(' '.join(dictn[k]))


ans = []
for ooo in range(int(input())):
	(n, m) = list(map(int, input().split()))
	vn = []
	vm = []
	for i in range(n):
		vn.append(list(map(int, input().split())))
	for i in range(m):
		vm.append(list(map(int, input().split())))
	c = 1
	i = 0
	while c:
		if vn[0][0] in vm[i]:
			m1 = vm[i]
			c = 0
		i += 1
	vn.sort(key=lambda x: m1.index(x[0]))
	ans.append(vn)
for i in ans:
	for i1 in i:
		print(*i1)