#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m, f = -1;
    cin >> n >> m;
    vector<vector<int>> a(n);
    unordered_map<int, int> mp;
    for (int i = 0; i < n; ++i) {
      vector<int> x(m);
      for (int j = 0; j < m; ++j) cin >> x[j];
      a[i] = x;
      mp[x[0]] = i;
    }
    vector<vector<int>> b(m);
    for (int i = 0; i < m; ++i) {
      vector<int> x(n);
      for (int j = 0; j < n; ++j) cin >> x[j];
      b[i] = x;
      if (mp.find(x[0]) != mp.end()) f = i;
    }
    for (auto i : b[f]) {
      for (int j = 0; j < m; ++j) cout << a[mp[i]][j] << ' ';
      cout << '\n';
    }
  }
}
