#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    cin.ignore();
    map<int, vector<int>> r, c;
    vector<int> v;
    for (int i = 1; i <= n; i++) {
      int tmp = 0;
      for (int j = 1; j <= m; j++) {
        int x;
        cin >> x;
        if (j == 1) {
          tmp = x;
        }
        r[tmp].push_back(x);
      }
    }
    for (int i = 1; i <= m; i++) {
      for (int j = 1; j <= n; j++) {
        int x;
        cin >> x;
        c[i].push_back(x);
      }
    }
    for (auto i = r.begin(); i != r.end(); i++) {
      bool f = false;
      for (auto j = c.begin(); j != c.end(); j++) {
        if ((i->second)[0] == (j->second)[0]) {
          v = j->second;
          f = true;
          break;
        }
      }
      if (f) {
        break;
      }
    }
    for (int i = 0; i < v.size(); i++) {
      for (int j = 0; j < r[v[i]].size(); j++) {
        cout << r[v[i]][j] << " ";
      }
      cout << "\n";
    }
  }
  return 0;
}
