#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x << 1) + (x << 3) + (c ^ 48);
    c = getchar();
  }
  return x * f;
}
int t, n, m, a[250005], b[250005], f[505][505];
int main() {
  t = read();
  while (t--) {
    n = read(), m = read();
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) b[read()] = j;
    for (int i = 1; i <= m; i++)
      for (int j = 1; j <= n; j++) a[read()] = j;
    for (int i = 1; i <= n * m; i++) f[a[i]][b[i]] = i;
    for (int i = 1; i <= n; i++, putchar('\n'))
      for (int j = 1; j <= m; j++) printf("%d ", f[i][j]);
  }
  return 0;
}
