#include <bits/stdc++.h>
using namespace std;
void call() {
  int n, m;
  cin >> n >> m;
  int arr[n][m];
  int brr[m][n];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> arr[i][j];
    }
  }
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      cin >> brr[i][j];
    }
  }
  int ans[n][m];
  int index;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (arr[i][0] == brr[j][0]) {
        index = j;
      }
    }
  }
  for (int ix = 0, j = 0; ix < n; ix++, j++) {
    int k = brr[index][ix];
    for (int i = 0; i < n; i++) {
      if (arr[i][0] == k) {
        for (int l = 0; l < m; l++) {
          ans[j][l] = arr[i][l];
        }
        break;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cout << ans[i][j] << " ";
    }
    cout << endl;
  }
}
int main() {
  int T;
  cin >> T;
  while (T--) {
    call();
  }
  return 0;
}
