#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 228;
const int MAXN = 1e5 + 7;
const int NEUTRAL = -INF;
const long long MOD = 1e9 + 7;
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<int> > a(n, vector<int>(m)), b(m, vector<int>(n)), ans;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a[i][j];
    }
  }
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
      cin >> b[i][j];
    }
  }
  int cur;
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
      if (b[i][0] == a[j][0]) {
        ans.push_back(a[j]);
        cur = i;
      }
    }
  }
  for (int i = 1; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      if (b[cur][i] == a[j][0]) {
        ans.push_back(a[j]);
      }
    }
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cout << ans[i][j] << ' ';
    }
    cout << '\n';
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) solve();
  return 0;
}
