#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t, n, m, ra, ca;
  cin >> t;
  for (int u = 0; u < t; ++u) {
    cin >> n >> m;
    vector<vector<int>> r(n, vector<int>(m));
    vector<vector<int>> c(m, vector<int>(n));
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> r[i][j];
        if (r[i][j] == 1) ra = j;
      }
    }
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        cin >> c[i][j];
        if (c[i][j] == 1) ca = i;
      }
    }
    vector<int> p(n);
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < n; ++j) {
        if (r[i][ra] == c[ca][j]) {
          p[j] = i;
        }
      }
    }
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cout << r[p[i]][j] << " ";
      }
      cout << '\n';
    }
  }
  return 0;
}
