#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t;
  cin >> t;
  while (t--) {
    int n, m;
    int arr[501][501], b_arr[501][501];
    cin >> n >> m;
    int pos[250002];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> arr[i][j];
        pos[arr[i][j]] = j;
      }
    }
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        cin >> b_arr[i][j];
      }
    }
    int pos2[501];
    for (int i = 0; i < m; i++) {
      int flag = b_arr[i][0];
      pos2[i] = pos[flag];
    }
    int fin_arr[501][501];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        fin_arr[i][pos2[j]] = b_arr[j][i];
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << fin_arr[i][j] << " ";
      }
      cout << endl;
    }
  }
  return 0;
}
