#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1e3 + 23;
long long ans[MAXN][MAXN];
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long t;
  cin >> t;
  for (long long _ = 0; _ < t; ++_) {
    long long n, m;
    cin >> n >> m;
    vector<vector<long long>> a(n, vector<long long>(m));
    vector<vector<long long>> c(n, vector<long long>(m));
    vector<vector<long long>> b(n, vector<long long>(m));
    vector<vector<long long>> d(n, vector<long long>(m));
    for (long long i = 0; i < n; ++i) {
      for (long long j = 0; j < m; ++j) {
        cin >> a[i][j];
        c[i][j] = a[i][j];
      }
      sort(c[i].begin(), c[i].end());
    }
    for (long long j = 0; j < m; ++j) {
      for (long long i = 0; i < n; ++i) {
        cin >> b[i][j];
        d[i][j] = b[i][j];
      }
    }
    vector<long long> used(n);
    for (long long i = 0; i < n; ++i) {
      sort(d[i].begin(), d[i].end());
    }
    for (long long i = 0; i < n; ++i) {
      for (long long j = 0; j < n; ++j) {
        if (used[j]) {
          continue;
        }
        long long fl = true;
        for (long long k = 0; k < m; ++k) {
          if (d[i][k] != c[j][k]) {
            fl = false;
            break;
          }
        }
        if (fl) {
          for (long long k = 0; k < m; ++k) {
            ans[i][k] = a[j][k];
          }
          used[j] = true;
          break;
        }
      }
    }
    for (long long i = 0; i < n; ++i) {
      for (long long j = 0; j < m; ++j) {
        cout << ans[i][j] << " ";
      }
      cout << endl;
    }
  }
  return 0;
}
