#include <bits/stdc++.h>
using namespace std;
using ull = unsigned long long;
using ll = long long;
using ld = long double;
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    int a[n][m];
    set<int> st;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> a[i][j];
        if (!j) st.insert(a[i][0]);
      }
    }
    int zero = -1;
    int b[m][n];
    map<int, int> arr;
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        cin >> b[i][j];
        if (!j) {
          arr[b[i][j]] = i;
          if (st.find(b[i][j]) != st.end()) zero = b[i][j];
        }
      }
    }
    int first = 0;
    for (int i = 0; i < n; ++i)
      if (a[i][0] == zero) {
        first = i;
        break;
      }
    int ans[n][m];
    for (int i = 0; i < m; ++i) {
      int x = a[first][i];
      int pos = arr[x];
      for (int j = 0; j < n; ++j) {
        ans[j][i] = b[pos][j];
      }
    }
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) cout << ans[i][j] << ' ';
      cout << '\n';
    }
  }
  return 0;
}
