#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<int> a[n];
    vector<int> b[m];
    int is[n * m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        int x;
        cin >> x;
        a[i].push_back(x);
        is[x] = i;
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        int x;
        cin >> x;
        b[i].push_back(x);
      }
    }
    vector<vector<int>> v;
    for (auto h : b[0]) {
      v.push_back(a[is[h]]);
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << v[i][j] << " ";
      }
      cout << "\n";
    }
  }
}
