#include <bits/stdc++.h>
using namespace std;
void file() {
  freopen("game.in", "r", stdin);
  freopen("game.out", "w", stdout);
}
void boos() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
const long long INF = (long long)1e9 + 7ll;
const long long INF1 = 998244353;
const long long INF2 = (long long)1e9 + 9ll;
const long long LLINF = (long long)2e18;
const long long INTmx = (long long)1e9;
const long double EPS = (long double)1e-15;
const int N = 600;
const int M = 3e5 + 100;
int a[N][N];
int b[N][N];
int was[M];
int main() {
  boos();
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<int> g;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> a[i][j];
        was[a[i][j]] = i;
      }
    }
    for (int i = 1; i <= m; i++) {
      for (int j = 1; j <= n; j++) {
        int x;
        cin >> x;
        if (i == 1) g.push_back(was[x]);
      }
    }
    for (int i = 0; i < g.size(); i++) {
      for (int j = 1; j <= m; j++) {
        cout << a[g[i]][j] << " ";
      }
      cout << "\n";
    }
  }
}
