#include <bits/stdc++.h>
using namespace std;
bool cmp(vector<int> a, vector<int> b) { return a[0] < b[0]; }
vector<int>* bin_search(int a, vector<vector<int>>& b) {
  int r = b.size();
  int l = 0;
  while (r - l > 1) {
    int m = (r + l) / 2;
    if (b[m][0] <= a)
      l = m;
    else
      r = m;
  }
  if (b[l][0] != a)
    return NULL;
  else
    return &b[l];
}
int main() {
  int t;
  cin >> t;
  for (int cnt = 0; cnt < t; cnt++) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> row(n, vector<int>(m));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> row[i][j];
    vector<vector<int>> column(m, vector<int>(n));
    for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++) cin >> column[i][j];
    sort(row.begin(), row.end(), cmp);
    sort(column.begin(), column.end(), cmp);
    vector<vector<int>> answ(n, vector<int>(m));
    for (auto& i : row) {
      vector<int>* c = bin_search(i[0], column);
      if (c != NULL) {
        vector<int> x = *c;
        answ[0] = i;
        for (int i = 0; i < n; i++) answ[i][0] = x[i];
        break;
      }
    }
    for (int i = 1; i < n; i++) answ[i] = *bin_search(answ[i][0], row);
    for (auto& i : answ) {
      for (auto& j : i) cout << j << ' ';
      cout << endl;
    }
  }
}
