#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, m;
  cin >> n >> m;
  map<long long, vector<long long>> rows;
  for (long long i = 0; i < n; i++) {
    long long x;
    cin >> x;
    vector<long long> temp(m);
    temp[0] = x;
    for (long long j = 1; j < m; j++) {
      cin >> temp[j];
    }
    rows[x] = temp;
  }
  vector<vector<long long>> coloumns(m, vector<long long>(n));
  for (long long i = 0; i < m; i++) {
    for (long long j = 0; j < n; j++) {
      cin >> coloumns[i][j];
    }
  }
  bool flag = false;
  for (long long k = 0; k < m; k++) {
    for (long long i = 0; i < n; i++) {
      long long x = coloumns[k][i];
      if (rows.count(x) == 0) {
        break;
      } else {
        flag = true;
      }
      for (long long j = 0; j < rows[x].size(); j++) {
        cout << rows[x][j] << " ";
      }
      cout << endl;
    }
    if (flag) break;
  }
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
