#include <bits/stdc++.h>
using namespace std;
int solve() {
  int n, m;
  cin >> n >> m;
  map<int, int> col1;
  vector<vector<int>> ans(n);
  vector<vector<int>> rows(n, vector<int>(m));
  for (vector<int> &i : rows) {
    for (int &j : i) cin >> j;
  }
  for (int j = 0; j < m; j++)
    for (int i = 0; i < n; i++) {
      int val;
      cin >> val;
      col1[val] = i;
    }
  for (vector<int> &i : rows) {
    ans[col1[i[0]]] = i;
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cout << ans[i][j] << " ";
    }
    cout << endl;
  }
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
