#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx2")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const long long maxn = 500;
long long t[maxn][maxn], ans[maxn][maxn], col[maxn * maxn + 1], kek[maxn];
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long T;
  cin >> T;
  while (T--) {
    long long n, m;
    cin >> n >> m;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) cin >> kek[j];
    }
    for (long long j = 0; j < m; j++) {
      for (long long i = 0; i < n; i++) {
        long long x;
        cin >> x;
        col[x] = j;
        t[j][i] = x;
      }
    }
    for (long long i = 0; i < m; i++) {
      long long c = col[kek[i]];
      for (long long j = 0; j < n; j++) {
        ans[j][i] = t[c][j];
      }
    }
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        cout << ans[i][j] << " ";
      }
      cout << "\n";
    }
  }
}
