#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (a > b) {
    swap(a, b);
  }
  while (a != 0) {
    b %= a;
    swap(a, b);
  }
  return b;
}
long long pnd(long long a, long long b) { return a * b / gcd(a, b); }
int main() {
  ios::sync_with_stdio(false);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> A(n, vector<int>(m, 0)), B(m, vector<int>(n, 0));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> A[i][j];
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> B[i][j];
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (A[0][0] == B[i][j]) {
          swap(B[0], B[i]);
          i = m;
          break;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      int k = B[0][i];
      int ind = 0;
      for (; ind < n && k != A[ind][0]; ind++) {
      }
      for (int j = 0; j < m; j++) {
        cout << A[ind][j] << " ";
      }
      cout << "\n";
    }
  }
  return 0;
}
