#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
template <typename T>
using v = vector<T>;
template <typename... T>
using tup = tuple<T...>;
template <typename T1, typename T2>
using pa = pair<T1, T2>;
const ld PI = 3.1415926535;
const ll MOD = 1e9 + 7;
ll gcd(ll a, ll b) {
  if (b == 0) {
    return a;
  } else {
    return gcd(b, a % b);
  }
}
void solve() {
  ll n, m;
  cin >> n >> m;
  v<v<ll>> a(n, v<ll>(m));
  map<ll, ll> x;
  for (ll i = 0; i < n; ++i) {
    for (ll j = 0; j < m; ++j) {
      cin >> a[i][j];
      x[a[i][j]] = j;
    }
  }
  v<v<ll>> b(m, v<ll>(n));
  for (ll i = 0; i < m; ++i) {
    for (ll j = 0; j < n; ++j) {
      cin >> b[i][j];
    }
  }
  map<ll, v<ll>> y;
  for (v<ll>& z : b) {
    y[x[z[0]]] = z;
  }
  v<v<ll>> table(n, v<ll>(m));
  for (pa<ll, v<ll>> p : y) {
    for (ll i = 0; i < p.second.size(); ++i) {
      table[i][p.first] = p.second[i];
    }
  }
  for (auto z : table) {
    for (auto zx : z) {
      cout << zx << ' ';
    }
    cout << '\n';
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  ll t = 1;
  cin >> t;
  for (ll i = 0; i < t; ++i) {
    solve();
  }
}
