#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  unordered_map<int, int> mp;
  cin >> n >> m;
  vector<vector<int>> ls;
  ls.resize(n, vector<int>(m));
  vector<int> ms;
  ms.resize(n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> ls[i][j];
      mp[ls[i][j]] = i;
    }
  }
  for (int j = 0; j < m; j++) {
    for (int i = 0; i < n; i++) {
      cin >> ms[i];
    }
  }
  int stind;
  for (int i = 0; i < n; i++) {
    stind = mp[ms[i]];
    for (int j = 0; j < m; j++) {
      cout << ls[stind][j] << " ";
    }
    cout << "\n";
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) {
    solve();
  }
  return 0;
}
