#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    map<long long int, long long int> m_x, m_y;
    long long int a, b[n][m];
    for (long long int j = 0; j < n; j++) {
      for (long long int k = 0; k < m; k++) {
        cin >> a;
        m_y[a] = k;
      }
    }
    for (long long int j = 0; j < m; j++) {
      for (long long int k = 0; k < n; k++) {
        cin >> a;
        m_x[a] = k;
        b[m_x[a]][m_y[a]] = a;
      }
    }
    for (long long int j = 0; j < n; j++) {
      for (long long int k = 0; k < m; k++) cout << b[j][k] << " ";
      cout << "\n";
    }
  }
  return 0;
}
