#include <bits/stdc++.h>
using namespace std;
int 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 arr[n][m];
    map<int, int> pos;
    for (int i = 0; i < n; i++) {
      int a;
      for (int j = 0; j < m; j++) {
        cin >> a;
        pos[a] = j;
      }
    }
    for (int i = 0; i < m; i++) {
      int b;
      for (int j = 0; j < n; j++) {
        cin >> b;
        arr[j][pos[b]] = b;
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << arr[i][j] << " ";
      }
      cout << endl;
    }
  }
  return 0;
}
