#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t;
  cin >> t;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    long long int a[n * m + 1];
    for (long long int i = 0; i < n; i++) {
      for (long long int j = 0; j < m; j++) {
        long long int x;
        cin >> x;
        a[x] = j;
      }
    }
    long long int b[m * n + 1];
    for (long long int i = 0; i < m; i++) {
      for (long long int j = 0; j < n; j++) {
        long long int y;
        cin >> y;
        b[y] = j;
      }
    }
    long long int c[n][m];
    for (long long int i = 1; i <= n * m; i++) c[b[i]][a[i]] = i;
    for (long long int i = 0; i < n; i++) {
      for (long long int j = 0; j < m; j++) cout << c[i][j] << " ";
      cout << endl;
    }
  }
  return 0;
}
