#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> rows(n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int a;
      cin >> a;
      rows[i].push_back(a);
    }
  }
  vector<vector<int>> columns(m);
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      int a;
      cin >> a;
      columns[i].push_back(a);
    }
  }
  int f = rows[0][0], fcol;
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      if (columns[i][j] == f) {
        fcol = i;
        break;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    int a = columns[fcol][i], req_row;
    for (int j = 0; j < n; j++) {
      if (rows[j][0] == a) {
        req_row = j;
        break;
      }
    }
    for (int j = 0; j < m; j++) {
      cout << rows[req_row][j] << " ";
    }
    cout << endl;
  }
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
