#include <bits/stdc++.h>
using namespace std;
void solution() {
  int n, m;
  cin >> n >> m;
  int rows[n][m];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> rows[i][j];
    }
  }
  int cols[m][n];
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      cin >> cols[i][j];
    }
  }
  int el = cols[0][0];
  for (int i = 0; i < n; i++) {
    if (find(rows[i], rows[i] + m, el) != rows[i] + m) {
      int l = find(rows[i], rows[i] + m, el) - rows[i];
      int arrangement[n];
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          if (cols[0][j] == rows[k][l]) {
            arrangement[j] = k;
            break;
          }
        }
      }
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          cout << rows[arrangement[i]][j] << " ";
        }
        cout << endl;
      }
      return;
    }
  }
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int count, counter = 0;
  cin >> count;
  while (counter++ < count) {
    solution();
  }
  return 0;
}
