#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {1, -1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
const double PI = 3.1415926535897932384626433832795;
const double eps = 1e-9;
const int MOD1 = 1e9 + 7;
const int MOD2 = 998244353;
int a[510][510];
int b[510][510];
int ans[510][510];
int pos[510];
void solve() {
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) cin >> a[i][j];
  for (int i = 1; i <= m; ++i)
    for (int j = 1; j <= n; ++j) cin >> b[i][j];
  for (int i = 1; i <= n; ++i) {
    bool ch = 0;
    for (int j = 1; j <= n; ++j) {
      for (int k = 1; k <= m; ++k) {
        if (b[1][i] == a[j][k]) {
          for (int z = 1; z <= m; ++z) ans[i][z] = a[j][z];
          ch = 1;
          break;
        }
      }
      if (ch) break;
    }
  }
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) cout << ans[i][j] << ' ';
    cout << '\n';
  }
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) b[j][i] = 0, a[i][j] = 0, ans[i][j] = 0;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int T = 1;
  cin >> T;
  while (T--) solve();
  return 0;
}
