#include <bits/stdc++.h>
using namespace std;
bool isprime(long long x) {
  if (x == 2) return true;
  if (x == 3) return true;
  for (long long i = 2; i * i <= x; i++) {
    if (x % i == 0) return false;
  }
  return true;
}
bool issort(long long a[], long long n) {
  for (long long i = 1; i < n; i++) {
    if (a[i - 1] >= a[i]) {
      return false;
    }
  }
  return true;
}
void solve() {
  long long n, m, x, N, M;
  cin >> n >> m;
  long long b[n][m];
  N = n, M = m;
  map<long long, long long> mp;
  while (N > 0) {
    for (long long i = 0; i < m; i++) {
      cin >> x;
      mp[x] = i;
    }
    N--;
  }
  while (M > 0) {
    for (long long i = 0; i < n; i++) {
      cin >> x;
      b[i][mp[x]] = x;
    }
    M--;
  }
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cout << b[i][j] << " ";
    }
    cout << "\n";
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
