#include <bits/stdc++.h>
using namespace std;
long long a[510][510], b[510][510];
long long ord[510];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int T;
  cin >> T;
  while (T--) {
    int n, m;
    cin >> n >> m;
    long long y;
    for (int i = 1; i <= n; ++i) {
      for (int j = 1; j <= m; ++j) {
        cin >> a[i][j];
        if (a[i][j] == 1) {
          y = j;
        }
      }
    }
    long long z;
    for (int i = 1; i <= m; ++i) {
      for (int j = 1; j <= n; ++j) {
        cin >> b[i][j];
        if (b[i][j] == 1) {
          z = i;
        }
      }
    }
    for (int i = 1; i <= n; ++i) {
      long long x = b[z][i];
      for (int j = 1; j <= n; ++j) {
        if (a[j][y] == x) {
          ord[i] = j;
          break;
        }
      }
    }
    for (int i = 1; i <= n; ++i) {
      int k = ord[i];
      for (int j = 1; j <= m; ++j) {
        cout << a[k][j] << " ";
      }
      cout << "\n";
    }
  }
}
