#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
using namespace std;
int main() {
  {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
  };
  long long _;
  cin >> _;
  for (_; _; _--) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> rows(n, vector<int>(m));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) cin >> rows[i][j];
    }
    vector<vector<int>> cols(m, vector<int>(n));
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) cin >> cols[i][j];
    }
    vector<int> row(n * m, 0);
    vector<int> col(n * m, 0);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) col[rows[i][j] - 1] = j;
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) row[cols[i][j] - 1] = j;
    }
    vector<vector<int>> ans(n, vector<int>(m));
    for (int i = 0; i < n * m; i++) ans[row[i]][col[i]] = i + 1;
    for (auto h : ans) {
      for (auto u : h) cout << u << " ";
      cout << "\n";
    }
  }
}
