#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  for (int k = 0; k < t; k++) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> a(max(n, m), vector<int>(max(n, m)));
    vector<vector<int>> id(n * m, vector<int>(2));
    vector<vector<int>> c(n, vector<int>(m));
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
        id[a[i][j] - 1][1] = j;
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> a[i][j];
        id[a[i][j] - 1][0] = j;
      }
    }
    for (int k = 0; k < n * m; k++) {
      int i = id[k][0], j = id[k][1];
      c[i][j] = k + 1;
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << c[i][j] << ' ';
      }
      cout << '\n';
    }
  }
}
