#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
template <class A>
istream &operator>>(istream &in, vector<A> &a) {
  for (auto &i : a) {
    in >> i;
  }
  return in;
}
template <class B>
ostream &operator<<(ostream &out, vector<B> &a) {
  for (auto &i : a) {
    out << i << " ";
  }
  out << "\n";
  return out;
}
map<long long, long long> get_p(long long x) {
  map<long long, long long> primes;
  for (long long(d) = (2); d < sqrt(x) + 1; d++) {
    while (x % d == 0) {
      x /= d;
      primes[d]++;
    }
  }
  if (x > 1) {
    primes[x]++;
  }
  return primes;
}
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long solve() {
  long long n, m;
  cin >> n >> m;
  vector<long long> y(n * m), x(n * m);
  for (long long(i) = (0); i < n; i++) {
    for (long long(j) = (0); j < m; j++) {
      long long t;
      cin >> t;
      t--;
      x[t] = j;
    }
  }
  for (long long(j) = (0); j < m; j++) {
    for (long long(i) = (0); i < n; i++) {
      long long t;
      cin >> t;
      t--;
      y[t] = i;
    }
  }
  vector<vector<long long>> mat(n, vector<long long>(m));
  for (long long(i) = (0); i < n * m; i++) {
    mat[y[i]][x[i]] = i + 1;
  }
  for (long long(i) = (0); i < n; i++) {
    for (long long(j) = (0); j < m; j++) {
      cout << mat[i][j] << " ";
    }
    cout << "\n";
  }
  return 1;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  long long tt = 1;
  cin >> tt;
  while (tt--) {
    solve();
  }
  return 0;
}
