------
## 最终结论
```python
# Function to restore the table
def restore_table(n, m, rows, columns):
    # Create a dictionary to map the first element of each column to its index
    column_map = {columns[i][0]: i for i in range(m)}
    
    # Create the result table with None values
    result_table = [None] * n
    
    # Place each row in the correct position based on the column_map
    for row in rows:
        first_element = row[0]
        correct_column_index = column_map[first_element]
        for i in range(n):
            if result_table[i] is None or result_table[i][correct_column_index] == first_element:
                result_table[i] = row
                break
    
    return result_table

# Input reading and function calling
import sys

input_data = sys.stdin.read().strip().split()
index = 0

t = int(input_data[index])
index += 1

results = []

for _ in range(t):
    n, m = map(int, input_data[index:index+2])
    index += 2
    
    rows = []
    for _ in range(n):
        row = list(map(int, input_data[index:index+m]))
        index += m
        rows.append(row)
    
    columns = []
    for _ in range(m):
        column = list(map(int, input_data[index:index+n]))
        index += n
        columns.append(column)
    
    # Restore the table and add to results
    restored_table = restore_table(n, m, rows, columns)
    results.append(restored_table)

# Output results
for result in results:
    for line in result:
        print(' '.join(map(str, line)))
```