#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) {
    int n, m;
    cin >> n >> m;
    vector<int> num;
    vector<vector<int>> ans(n, vector<int>(m));
    map<int, pair<int, int>> mp;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        int x;
        cin >> x;
        num.push_back(x);
        mp[x].second = j;
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        int x;
        cin >> x;
        mp[x].first = j;
      }
    }
    for (int i : num) {
      ans[mp[i].first][mp[i].second] = i;
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << ans[i][j] << " ";
      }
      cout << endl;
    }
  }
}
