#include <bits/stdc++.h>
using namespace std;
const signed inf = 1000000100;
const long long inf64 = 1ll * inf * inf;
const long long mod = 1e9 + 7;
mt19937 rng(0);
void run() {
  long long n, m;
  cin >> n >> m;
  vector<vector<long long>> rows(n, vector<long long>(m));
  vector<vector<long long>> cols(m, vector<long long>(n));
  vector<long long> row_id(n * m + 1, -1);
  for (long long i = 0; i < n; ++i) {
    for (auto &i : rows[i]) cin >> i;
  }
  for (long long i = 0; i < m; ++i) {
    for (auto &i : cols[i]) cin >> i;
  }
  for (long long i = 0; i < n; ++i) {
    row_id[rows[i][0]] = i;
  }
  vector<long long> p(n);
  for (auto &i : cols) {
    if (row_id[i[0]] == -1) continue;
    for (long long j = 0; j < n; ++j) {
      p[j] = row_id[i[j]];
    }
  }
  for (auto i : p) {
    for (auto &i : rows[i]) cout << i << ' ';
    cout << '\n';
  }
}
signed main() {
  iostream::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) {
    run();
    cout.flush();
  }
}
