#include <bits/stdc++.h>
using namespace std;
const long long int N = 2e5 + 7;
const long long int mod = 1e9 + 7;
map<long long int, long long int> mp;
void solve1() {
  long long int n, m, a;
  cin >> n >> m;
  long long int ar[n][m];
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) {
      cin >> ar[i][j];
      mp[ar[i][j]] = i;
    }
  }
  for (long long int q = 0; q < n; q++) {
    cin >> a;
    for (long long int i = 0; i < m; i++) {
      cout << ar[mp[a]][i] << " ";
    }
    cout << endl;
  }
  for (long long int i = 0; i < m - 1; i++) {
    for (long long int j = 0; j < n; j++) cin >> a;
  }
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  srand(time(0));
  long long int cghf = 1;
  cin >> cghf;
  while (cghf--) {
    solve1();
  }
}
