#include <bits/stdc++.h>
using namespace std;
int mi = INT_MAX, ma = INT_MIN;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int T;
  cin >> T;
  while (T--) {
    int n, m;
    cin >> n >> m;
    int rows[n][m];
    int cols[m][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> rows[i][j];
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> cols[i][j];
      }
    }
    vector<int> ans;
    int temp, col = -1;
    for (int i = 0; i < n; i++) {
      temp = cols[0][i];
      if (col = -1) {
        for (int i = 0; i < n; i++) {
          for (int j = 0; j < m; j++) {
            if (temp == rows[i][j]) {
              col = j;
              break;
            }
          }
        }
      }
      for (int j = 0; j < n; j++) {
        if (temp == rows[j][col]) {
          ans.push_back(j);
        }
      }
    }
    for (int x : ans) {
      for (int i = 0; i < m; i++) {
        cout << rows[x][i] << " ";
      }
      cout << endl;
    }
    ans.clear();
  }
  return 0;
}
