#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> a(n, vector<int>(m));
    map<int, vector<int>> raws;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
      }
      raws[a[i][0]] = a[i];
    }
    for (int j = 0; j < m; j++) {
      for (int i = 0; i < n; i++) {
        cin >> a[i][j];
      }
      if (raws.find(a[0][j]) != raws.end()) {
        for (int i = 0; i < n; i++) {
          for (int x : raws[a[i][j]]) {
            cout << x << ' ';
          }
          cout << '\n';
        }
      }
    }
  }
  return 0;
}
