#include <bits/stdc++.h>
using namespace std;
long long n, m, i, o, c, t, f[250010], x;
vector<long long> a[250010], b[250010], v1;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (i = 0; i < n; i++) {
      a[i].clear();
      for (o = 0; o < m; o++) {
        cin >> c;
        a[i].push_back(c);
        f[a[i][o]] = i;
      }
    }
    vector<long long> v;
    for (i = 0; i < m; i++) {
      for (o = 0; o < n; o++) {
        v.push_back(a[o][i]);
      }
    }
    sort(v.begin(), v.end());
    for (i = 0; i < m; i++) {
      b[i].clear();
      for (o = 0; o < n; o++) {
        cin >> c;
        b[i].push_back(c);
      }
      v1 = b[i];
      sort(v1.begin(), v1.end());
      if (v1 == v) x = i;
    }
    for (i = 0; i < n; i++) {
      long long y = f[b[x][i]];
      for (o = 0; o < m; o++) {
        cout << a[y][o] << " ";
      }
      cout << "\n";
    }
  }
  return 0;
}
