#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> v(n);
  unordered_map<int, int> mm;
  for (int i = 0; i < n; i++) {
    v[i].resize(m);
    for (int j = 0; j < m; j++) {
      cin >> v[i][j];
      mm[v[i][j]] = i;
    }
  }
  vector<int> col;
  int t;
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      cin >> t;
      if (i == 0) col.push_back(t);
    }
  }
  for (auto x : col) {
    int t = mm[x];
    for (auto y : v[t]) cout << y << " ";
    cout << endl;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
