#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  for (int k = 0; k < t; k++) {
    int n, m;
    cin >> n >> m;
    int prod = n * m;
    int arr[2][prod + 1];
    int num;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> num;
        arr[1][num] = j;
      }
    }
    for (int j = 0; j < m; j++) {
      for (int i = 0; i < n; i++) {
        cin >> num;
        arr[0][num] = i;
      }
    }
    int ans[n][m];
    for (int i = 1; i <= prod; i++) {
      int r = arr[0][i];
      int c = arr[1][i];
      ans[r][c] = i;
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << ans[i][j] << " ";
      }
      cout << endl;
    }
  }
  return 0;
}
