#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    unordered_map<long long, vector<long long> > mp;
    vector<long long> x;
    long long it;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        cin >> it;
        x.push_back(it);
      }
      mp[x[0]] = x;
      x.clear();
    }
    long long y[m][n];
    for (long long i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> y[i][j];
      }
    }
    for (int i = 0; i < m; i++) {
      for (int k = 0; k < n; k++) {
        if (mp.find(y[i][k]) == mp.end()) continue;
        for (auto &item : mp[y[i][k]]) {
          cout << item << " ";
        }
        cout << "\n";
      }
    }
  }
  return 0;
}
