#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const long long inf = (1000000000 + 7);
int num[510][510], col[510][510];
int p[510 * 510 + 100];
void solve() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> num[i][j];
    }
  }
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      cin >> col[i][j];
      p[col[i][j]] = j;
    }
  }
  int ans[n][m];
  for (int i = 0; i < n; i++) {
    int k = p[num[i][0]];
    for (int j = 0; j < m; j++) {
      ans[k][j] = num[i][j];
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cout << ans[i][j] << " ";
    }
    cout << "\n";
  }
}
void Task() {
  int test;
  cin >> test;
  for (int i = 1; i <= test; i++) {
    solve();
  }
}
int main() {
  Task();
  return 0;
}
