#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t) {
    int n, m;
    cin >> n >> m;
    vector<vector<int> > str(n, vector<int>(m));
    vector<vector<int> > stolb(m, vector<int>(n));
    vector<int> ans(n);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> str[i][j];
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> stolb[i][j];
      }
    }
    for (int k = 0; k < m; k++) {
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          if (stolb[0][i] == str[j][k]) {
            for (int h = 0; h < m; h++) cout << str[j][h] << " ";
            cout << endl;
            break;
          }
        }
      }
    }
    t--;
  }
}
