#include <bits/stdc++.h>
template <class T>
inline void read(T &x) {
  char c = getchar(), f = 0;
  x = 0;
  while (!isdigit(c)) f = (c == '-'), c = getchar();
  while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
  x = f ? -x : x;
}
using namespace std;
const int N = 10000 + 5;
const int M = 100000 + 5;
const int HA = 998244353;
int n, m, a[505][505], b[505][505], lef[M], pla[M], ans[M];
void solve() {
  for (int i = (1); i <= (n); i++) {
    for (int j = (1); j <= (m); j++) {
      a[i][j] = b[i][j] = 0;
    }
  }
  read(n), read(m);
  for (int i = (1); i <= (n); i++) {
    for (int j = (1); j <= (m); j++) {
      read(a[i][j]);
      pla[a[i][j]] = i;
    }
  }
  int tot = 0;
  for (int i = (1); i <= (m); i++) {
    for (int j = (1); j <= (n); j++) {
      read(b[i][j]);
      ans[++tot] = pla[b[i][j]];
    }
  }
  for (int i = (1); i <= (n); i++) {
    for (int j = (1); j <= (m); j++) {
      cout << a[ans[i]][j] << " ";
    }
    cout << "\n";
  }
}
int main() {
  int t;
  read(t);
  while (t--) solve();
  return 0;
}
