#include <bits/stdc++.h>
using namespace std;
int n, m;
int x[501];
int a[501][501];
void searc() {
  int last = 0;
  for (int j = 1; j <= m; j++) {
    for (int k = 1; k <= n; k++)
      if (x[k] == a[1][j]) {
        last = j;
        break;
      }
  }
  for (int i = 1; i <= n; i++) a[i][last] = x[i];
}
int main() {
  ios::sync_with_stdio(0);
  iostream::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    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 >> x[j];
      searc();
    }
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) cout << a[i][j] << ' ';
      cout << '\n';
    }
  }
}
