#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
vector<long long> v[250001];
vector<long long> o;
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 u;
    for (long long i = (0); i < (n); i++) {
      cin >> u;
      v[u].push_back(u);
      int b;
      for (long long j = (0); j < (m - 1); j++) {
        cin >> b;
        v[u].push_back(b);
      }
    }
    for (long long i = (0); i < (m); i++) {
      int a;
      cin >> a;
      if ((int)v[a].size() > 0) {
        o.push_back(a);
        for (long long j = (0); j < (n - 1); j++) {
          cin >> a;
          o.push_back(a);
        }
        continue;
      }
      for (long long j = (0); j < (n - 1); j++) {
        cin >> a;
      }
    }
    for (auto f : o) {
      for (auto g : v[f]) {
        cout << g << " ";
      }
      if ((int)v[f].size() > 0) {
        v[f].clear();
      }
      cout << endl;
    }
    if (o.size() > 0) {
      o.clear();
    }
  }
  return 0;
}
