#include <bits/stdc++.h>
using namespace std;
int a[505][505], b[505][505], num[250005], c[505];
int read() {
  int A;
  bool K;
  char C;
  C = A = K = 0;
  while (C < '0' || C > '9') K |= C == '-', C = getchar();
  while (C > '/' && C < ':') A = (A << 3) + (A << 1) + (C ^ 48), C = getchar();
  return (K ? -A : A);
}
void write(int X) {
  if (X < 0) putchar('-'), X = -X;
  if (X > 9) write(X / 10);
  putchar(X % 10 | 48);
}
int main() {
  int t, i, j, n, m;
  t = read();
  while (t--) {
    n = read(), m = read();
    for (i = 1; i <= (n); i++)
      for (j = 1; j <= (m); j++) a[i][j] = read();
    for (j = 1; j <= (m); j++)
      for (i = 1; i <= (n); i++) b[j][i] = read(), num[b[j][i]] = j;
    for (j = 1; j <= (m); j++) c[j] = num[a[1][j]];
    for (i = 1; i <= (n); i++) {
      for (j = 1; j <= (m); j++) write(b[c[j]][i]), putchar(' ');
      putchar('\n');
    }
  }
  return 0;
}
