#include <bits/stdc++.h>
using namespace std;
long long n, m, a[600][600], T, u, c[600][600];
pair<long long, long long> v[300000];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> T;
  for (int i = 1; i <= T; i++) {
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        cin >> u;
        v[u].second = j;
      }
    for (int i = 1; i <= m; i++)
      for (int j = 1; j <= n; j++) {
        cin >> u;
        v[u].first = j;
      }
    for (int i = 1; i <= n * m; i++) c[v[i].first][v[i].second] = i;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) cout << c[i][j] << " ";
      cout << '\n';
    }
  }
  return 0;
}
