#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  long long num_of_req, row, col, num;
  cin >> num_of_req;
  for (int i = 0; i < num_of_req; ++i) {
    cin >> row >> col;
    vector<long long> ext(row);
    bool f = true, f0 = true;
    vector<vector<long long>> ans(row, vector<long long>(col));
    vector<vector<long long>> ans0(row);
    for (int j = 0; j < row; ++j) {
      for (int x = 0; x < col; ++x) {
        cin >> ans[j][x];
      }
    }
    for (int j = 0; j < col; ++j) {
      for (int x = 0; x < row; ++x) {
        if (f) {
          cin >> ext[x];
          if (ext[x] == ans[0][0]) {
            f0 = false;
          }
        } else {
          cin >> num;
        }
      }
      if (!f0) {
        f = false;
      }
    }
    for (int j = 0; j < row; ++j) {
      for (int x = 0; x < row; ++x) {
        if (ans[j][0] == ext[x]) {
          ans0[x] = ans[j];
        }
      }
    }
    for (int j = 0; j < row; ++j) {
      cout << ans0[j][0];
      for (int x = 1; x < col; ++x) {
        cout << " " << ans0[j][x];
      }
      cout << "\n";
    }
  }
  return 0;
}
