#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using vi = vector<int>;
using pi = pair<int, int>;
using vpi = vector<pi>;
using vll = vector<ll>;
const int N = 600;
const int MOD = 1e9 + 7;
template <class T>
bool ckmin(T &a, T b) {
  return a > b ? a = b, true : false;
}
template <class T>
bool ckmax(T &a, T b) {
  return a < b ? a = b, true : false;
}
int a[N][N];
void solve() {
  int n, m;
  cin >> n >> m;
  vector<int> v(n * m + 1);
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a[i][j];
      v[a[i][j]] = i;
    }
  }
  vector<int> b(n);
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
      cin >> b[j];
    }
  }
  vector<int> ans(n);
  for (int i = 0; i < n; ++i) {
    ans[i] = v[b[i]];
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cout << a[ans[i]][j] << " ";
    }
    cout << "\n";
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}
