#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, c, d, i = 0, j = 0, n = 0, t = 0, l = 0, m = 0;
  string s, g;
  cin >> t;
  while (t--) {
    cin >> a >> b;
    int x[a + 1][b + 1], y[b + 1][a + 1];
    for (i = 0; i < a; i++)
      for (j = 0; j < b; j++) cin >> x[i][j];
    for (i = 0; i < b; i++)
      for (j = 0; j < a; j++) cin >> y[i][j];
    l = 0;
    for (i = 0; i < b; i++)
      for (j = 0; j < a; j++)
        if (x[0][0] == y[i][j]) {
          l = i;
          break;
        }
    for (i = 0; i < a; i++)
      for (j = 0; j < a; j++)
        if (x[j][0] == y[l][i]) {
          for (n = 0; n < b; n++) cout << x[j][n] << " ";
          cout << "\n";
          break;
        }
  }
  return 0;
}
