#include <bits/stdc++.h>
const int INF = 2 * 1e9;
const long long int MOD = 1000000007;
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<int> > row(n, vector<int>(m));
  for (int(i) = 0; (i) < (n); (i)++) {
    for (int(j) = 0; (j) < (m); (j)++) cin >> row[i][j];
  }
  map<int, int> ma;
  for (int(i) = 0; (i) < (n); (i)++) {
    ma[row[i][0]] = i;
  }
  vector<vector<int> > col(m, vector<int>(n));
  for (int(i) = 0; (i) < (m); (i)++) {
    for (int(j) = 0; (j) < (n); (j)++) {
      cin >> col[i][j];
    }
  }
  for (int(i) = 0; (i) < (m); (i)++) {
    if (ma.count(col[i][0]) == 1) {
      for (int(i1) = 0; (i1) < (n); (i1)++) {
        int pos = ma[col[i][i1]];
        for (int(j1) = 0; (j1) < (m); (j1)++) {
          cout << row[pos][j1] << ' ';
        }
        cout << '\n';
      }
      return;
    }
  }
}
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cout.fixed;
  cout.precision(12);
  int t;
  cin >> t;
  for (int(i) = 0; (i) < (t); (i)++) solve();
  return 0;
}
