#include <bits/stdc++.h>
using namespace std;
int ans[501][501];
signed main() {
  cin.tie(0);
  cout.tie(0);
  ios::sync_with_stdio(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m, x;
    cin >> n >> m;
    map<int, vector<int> > q;
    for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j) cin >> x, q[x].push_back(j);
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) cin >> x, q[x].push_back(j);
    for (auto& e : q) ans[e.second[1]][e.second[0]] = e.first;
    for (int i = 0; i < n; ++i, cout << "\n")
      for (int j = 0; j < m; ++j) cout << ans[i][j] << " ";
  }
}
