#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t, a, b, n, m;
  cin >> t;
  vector<vector<int> > vn;
  vector<vector<int> > vm;
  vector<int> otv;
  vector<vector<int> > OTV;
  for (int q = 0; q < t; q++) {
    cin >> n >> m;
    vn.resize(n);
    vm.resize(m);
    OTV.resize(n);
    otv.resize(n);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a;
        vn[i].push_back(a);
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> a;
        vm[i].push_back(a);
      }
    }
    for (int i = 0; i < n; i++) {
      a = vn[i][0];
      for (int j = 0; j < m; j++) {
        for (int x = 0; x < n; x++) {
          if (a == vm[j][x]) {
            otv[i] = x;
            x = n;
            j = m;
          }
        }
      }
    }
    for (int z = 0; z < n; z++) {
      OTV[otv[z]] = vn[z];
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << OTV[i][j] << ' ';
      }
      cout << endl;
    }
    vm.clear();
    vn.clear();
  }
}
