#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    int arr[250010];
    int arr2[500 + 1][500 + 1];
    int k = 0;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> k;
        arr[k] = j;
      }
    }
    for (int i = 1; i <= m; i++) {
      for (int j = 1; j <= n; j++) {
        cin >> k;
        arr2[j][arr[k]] = k;
      }
    }
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cout << arr2[i][j] << "  ";
      }
      cout << endl;
    }
  }
  return 0;
}
