#include <bits/stdc++.h>
using namespace std;
const int imax = INT32_MAX;
const int imin = INT32_MIN;
const int mx = 1e6;
const int mod = 1e9 + 7;
template <class T>
void print(vector<T> vec) {
  for (T i : vec) cout << i << " ";
  cout << "\n";
}
template <class T>
void alloc(vector<vector<T>*> vec, T n) {
  for (auto v : vec) v->resize(n + 1);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int t = 1;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> a(n, vector<int>(m)), ans(n, vector<int>(m));
    vector<vector<int>> b(m, vector<int>(n));
    for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j) {
        int in;
        cin >> in;
        a[i][j] = in;
      }
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        int in;
        cin >> in;
        b[i][j] = in;
      }
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        auto it = find(b[j].begin(), b[j].end(), a[i][0]);
        if (it == b[j].end()) continue;
        int index = it - b[j].begin();
        ans[index] = a[i];
      }
    }
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) cout << ans[i][j] << " ";
      cout << "\n";
    }
  }
  return 0;
}
