#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long testcases = 1;
  cin >> testcases;
  while (testcases--) {
    long long n, m;
    string ele;
    cin >> n >> m;
    map<string, string> v;
    map<string, long long> m3;
    for (long long i = 0; i < n; i++) {
      string s = "";
      for (long long j = 0; j < m; j++) {
        string a;
        cin >> a;
        if (j == 0) {
          ele = a;
        }
        s += a;
        s += " ";
        if (j == 0) {
          m3[a]++;
        }
      }
      v[ele] = s;
    }
    bool ans = true;
    for (long long i = 0; i < m; i++) {
      for (long long j = 0; j < n; j++) {
        string a;
        cin >> a;
        if (j == 0) {
          if (m3[a]) {
            ans = true;
          }
        }
        if (ans) {
          cout << v[a] << endl;
        }
      }
      if (ans) ans = false;
    }
  }
  return 0;
}
