#include <bits/stdc++.h>
using namespace std;
const int64_t LINF = 9187201950435737471;
const int64_t nLINF = -9187201950435737472;
const int64_t INF = 2139062143;
const int nINF = -2139062144;
const uint64_t ULINF = numeric_limits<uint64_t>::max();
const int64_t MAXN = 2e5 + 15;
const int64_t MAXE = 1e5 + 15;
const double PI = acos(-1);
const int64_t MOD = 1e9 + 7;
const int64_t P = 29;
const double EPS = 1e-10;
auto seed = chrono::high_resolution_clock::now().time_since_epoch().count();
mt19937 rnd(seed);
bool isEqual(double a, double b) { return abs(a - b) <= EPS; }
inline void IO() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
}
template <typename T>
istream& operator>>(istream& in, vector<T>& a) {
  for (auto& i : a) in >> i;
  return in;
}
template <typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
  for (auto& i : a) {
    out << i << " ";
  }
  return out;
}
template <typename T, typename D>
istream& operator>>(istream& in, pair<T, D>& a) {
  in >> a.first >> a.second;
  return in;
}
template <typename T, typename D>
ostream& operator<<(ostream& out, const pair<T, D>& a) {
  out << a.first << " " << a.second;
  return out;
}
inline void solve() {
  int n, m;
  cin >> n >> m;
  vector<int> from_num_to_string(n * m + 1);
  vector<vector<int> > s(n);
  vector<vector<int> > ans(n, vector<int>(m));
  for (int i = 0; i < n; ++i) {
    s[i].resize(m);
    for (int j = 0; j < m; ++j) {
      cin >> s[i][j];
      from_num_to_string[s[i][j]] = i;
    }
  }
  for (int i = 1; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
      int x;
      cin >> x;
    }
  }
  for (int j = 0; j < n; ++j) {
    int x;
    cin >> x;
    int str = from_num_to_string[x];
    for (int i = 0; i < m; ++i) {
      ans[j][i] = s[str][i];
    }
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cout << ans[i][j] << " ";
    }
    cout << "\n";
  }
}
signed main() {
  IO();
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
