#include <bits/stdc++.h>
using namespace std;
template <typename... T>
void read(T&... args) {
  ((cin >> args), ...);
}
template <typename... T>
void write(T&&... args) {
  ((cout << args << " "), ...);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    long long a[n][m], b[m][n], in[n * m + 1];
    long long g;
    map<long long, long long> mp;
    for (long long i = 0; i < n; i++) {
      vector<long long> v1;
      for (long long j = 0; j < m; j++) {
        cin >> a[i][j];
        mp[a[i][j]] = i;
      }
    }
    for (long long i = 0; i < m; i++)
      for (long long j = 0; j < n; j++) cin >> b[i][j];
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        long long r = mp[b[0][i]];
        cout << a[r][j] << " ";
      }
      cout << "\n";
    }
  }
}
