#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7, maxn = 2e5 + 1, inf = 1e9, maxk = 20;
long long a[500][500];
long long b[500][500];
long long q[250000];
void solve() {
  long long n, m;
  cin >> n >> m;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[j][i];
      q[a[j][i] - 1] = i;
    }
  }
  for (long long j = 0; j < m; j++)
    for (long long i = 0; i < n; i++) {
      cin >> b[i][j];
    }
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cout << a[j][q[b[i][0] - 1]] << ' ';
    }
    cout << '\n';
  }
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) solve();
}
