#include <bits/stdc++.h>
using namespace std;
long long t, n, m, k, a[300010], q, l, r;
long long row[510][510], col[510][510], mat[510][510];
map<long long, long long> h;
long long ord[250010];
int32_t main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (long long i = 1; i <= n; i++) {
      for (long long j = 1; j <= m; j++) {
        cin >> row[i][j];
      }
    }
    for (long long j = 1; j <= m; j++) {
      for (long long i = 1; i <= n; i++) {
        cin >> col[i][j];
      }
    }
    long long val = col[1][1];
    long long f = 0;
    for (long long i = 1; (i <= n) && (f == 0); i++) {
      for (long long j = 1; j <= m; j++) {
        if (row[i][j] == val) {
          f = i;
          break;
        }
      }
    }
    for (long long j = 1; j <= m; j++) {
      ord[row[f][j]] = j;
    }
    for (long long i = 1; i <= n; i++) {
      for (long long j = 1; j <= m; j++) {
        mat[i][ord[col[1][j]]] = col[i][j];
      }
    }
    for (long long i = 1; i <= n; i++) {
      for (long long j = 1; j <= m; j++) {
        cout << mat[i][j] << " ";
      }
      cout << "\n";
    }
  }
  return 0;
}
