#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  int a[n][m];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) cin >> a[i][j];
  }
  int b[m][n];
  bool flag = false;
  int index = -1;
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      cin >> b[i][j];
      if (b[i][j] == a[0][0] && !flag) {
        flag = true;
        index = i;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    int curr = b[index][i];
    for (int j = 0; j < n; j++) {
      if (a[j][0] == curr) {
        for (int k = 0; k < m; k++) cout << a[j][k] << " ";
        cout << endl;
      }
    }
  }
}
int main() {
  long long int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
}
