#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m, x;
    cin >> n >> m;
    int grid[n][m];
    vector<vector<int>> v(n);
    vector<int> u(m);
    map<int, int> ind;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> x;
        ind[x] = i;
        v[i].push_back(x);
      }
    }
    for (int i = 0; i < m; i++) {
      u.clear();
      for (int j = 0; j < n; j++) {
        cin >> x;
        u.push_back(x);
      }
    }
    for (int i = 0; i < n; i++) {
      int it = ind[u[i]];
      for (int j = 0; j < m; j++) {
        grid[i][j] = v[it][j];
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << grid[i][j] << " ";
      }
      cout << '\n';
    }
  }
  return 0;
}
