#include <bits/stdc++.h>
using namespace std;
template <typename tmp>
void input(vector<tmp>& vc) {
  for (auto& x : vc) cin >> x;
}
template <typename tmp>
void output(vector<tmp>& vc, string endd = " ", string endll = "\n") {
  for (auto& x : vc) cout << x << endd;
  cout << endll;
}
int main() {
  int t;
  cin >> t;
  for (int y = 0; y < t; y++) {
    int n, m;
    cin >> n >> m;
    vector<set<int>> vc(n);
    vector<vector<int>> vc1(n, vector<int>(m));
    set<int> s1;
    int tmp;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> vc1[i][j];
        vc[i].insert(vc1[i][j]);
      }
    }
    vector<set<int>> vc2(n);
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        cin >> tmp;
        vc2[j].insert(tmp);
      }
    }
    for (int i = 0; i < n; ++i) {
      output(vc1[(find(vc.begin(), vc.end(), vc2[i]) - vc.begin())]);
    }
  }
}
