#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  for (int k = 0; k < t; k++) {
    int n, m;
    cin >> n >> m;
    vector<vector<int> > matr(n);
    for (int i = 0; i < n; i++) {
      matr[i].resize(m);
      for (int j = 0; j < m; j++) cin >> matr[i][j];
    }
    for (int i = 0; i < m; i++) {
      int a;
      cin >> a;
      bool f = false;
      int num;
      for (int j = 0; j < n; j++) {
        if (matr[j][0] == a) {
          f = true;
          num = j;
          break;
        }
      }
      if (f) {
        swap(matr[num], matr[0]);
        int last = 1;
        for (int e = 0; e < n - 1; e++) {
          cin >> a;
          for (int j = last; j < n; j++) {
            if (matr[j][0] == a) {
              swap(matr[j], matr[last]);
              last++;
              continue;
            }
          }
        }
      } else {
        for (int j = 0; j < n - 1; j++) {
          cin >> a;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) cout << matr[i][j] << ' ';
      cout << endl;
    }
  }
  return 0;
}
