#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  for (; t > 0; --t) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> vec(n, vector<int>(m));
    vector<int> mp(n * m + 1);
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> vec[i][j];
        mp[vec[i][j]] = i;
      }
    }
    for (int i = 0; i < n; ++i) {
      int a;
      cin >> a;
      for (int j = 0; j < m; ++j) {
        cout << vec[mp[a]][j] << ' ';
      }
      cout << '\n';
    }
    string str;
    for (int j = 0; j < m; ++j) {
      getline(cin, str);
    }
  }
  return 0;
}
