#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  int mat[n][m];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> mat[i][j];
    }
  }
  int p = 0;
  bool is = false;
  for (int j = 0; j < n; j++) {
    int temp;
    cin >> temp;
    for (; p < m; p++) {
      for (int i = 0; i < n; i++) {
        if (mat[i][p] == temp) {
          is = true;
          for (int k = 0; k < m; k++) {
            cout << mat[i][k] << " ";
          }
          cout << endl;
          break;
        }
      }
      if (is) {
        break;
      }
    }
  }
  for (int j = 1; j < m; j++) {
    for (int i = 0; i < n; i++) {
      int temp;
      cin >> temp;
    }
  }
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
