#include <bits/stdc++.h>
using namespace std;
int t, n, m, a[510][510], res[510][510], row[510], pos[250010];
void init() {
  for (int i = 0; i < n; i++) pos[a[i][0]] = i;
}
bool check() {
  for (int i = 0; i < n; i++)
    if (row[0] == a[i][0]) return true;
  return false;
}
void cal() {
  for (int i = 0; i < n; i++) {
    int p = pos[row[i]];
    for (int j = 0; j < m; j++) res[i][j] = a[p][j];
  }
}
int main() {
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> a[i][j];
    init();
    for (int j = 0; j < m; j++) {
      for (int i = 0; i < n; i++) cin >> row[i];
      if (check()) cal();
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) cout << res[i][j] << " ";
      cout << "\n";
    }
  }
}
