#include <bits/stdc++.h>
using namespace std;
const int modP = 1e9 + 7;
const long long oo = 1000000000000000LL;
const int maxN = 1000;
int a[maxN][maxN], c[maxN * maxN];
int main() {
  int test;
  cin >> test;
  while (test--) {
    int m, n;
    cin >> m >> n;
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        int x;
        cin >> x;
        c[x] = j;
      }
    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m; ++i) {
        int x;
        cin >> x;
        a[i][c[x]] = x;
      }
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) cout << a[i][j] << " ";
      cout << endl;
    }
  }
}
