#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > m1;
map<int, int> d;
vector<vector<int> > m2;
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    int n, m;
    cin >> n >> m;
    m1.resize(n);
    m2.resize(n);
    d.clear();
    for (int j = 0; j < n; ++j) {
      for (int j1 = 0; j1 < m; ++j1) {
        int dop;
        cin >> dop;
        m1[j].push_back(dop);
      }
    }
    for (int j = 0; j < m; ++j) {
      for (int j1 = 0; j1 < n; ++j1) {
        int dop;
        cin >> dop;
        d[dop] = j1;
      }
    }
    for (int j = 0; j < n; ++j) {
      int dop = d[m1[j][0]];
      m2[dop] = m1[j];
    }
    for (int j = 0; j < n; ++j) {
      for (int j1 = 0; j1 < m2[j].size(); ++j1) {
        if (j1 < m - 1) {
          cout << m2[j][j1] << ' ';
        } else {
          cout << m2[j][j1] << endl;
        }
      }
    }
    m1.clear();
    m2.clear();
    d.clear();
  }
  return 0;
}
