#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n, m;
int r[N][N], c[N][N];
inline void solve() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> r[i][j];
  for (int i = 1; i <= m; i++)
    for (int j = 1; j <= n; j++) cin >> c[i][j];
  int res[N];
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      for (int k = 1; k <= m; k++) {
        if (r[j][k] == c[1][i]) {
          res[i] = j;
          break;
        }
      }
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) cout << r[res[i]][j] << " ";
    cout << endl;
  }
}
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
