#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> a(n, vector<int>(m)), b(m, vector<int>(n)),
        ans(n, vector<int>(m));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> b[i][j];
      }
    }
    int first = -1;
    for (int i = 0; i < n; i++) {
      bool ok = false;
      for (int j = 0; j < m; j++) {
        if (a[i][j] == b[0][0]) {
          ok = true;
        }
      }
      if (ok) {
        first = i;
        break;
      }
    }
    map<int, int> id;
    for (int i = 0; i < m; i++) {
      id[b[i][0]] = i;
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        ans[j][i] = b[id[a[first][i]]][j];
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << ans[i][j] << ' ';
      }
      cout << '\n';
    }
  }
  return 0;
}
