#include <bits/stdc++.h>
using namespace std;
long long a[505][505], b[505][505];
struct node {
  long long x, y, num;
} c[1000005];
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> a[i][j];
        c[a[i][j]].x = i;
        c[a[i][j]].y = j;
      }
    }
    for (int i = 1; i <= m; i++) {
      for (int j = 1; j <= n; j++) {
        cin >> b[i][j];
      }
    }
    for (int j = 1; j <= n; j++) {
      int co = c[b[1][j]].x;
      for (int i = 1; i <= m; i++) {
        if (i == 1)
          cout << a[co][i];
        else
          cout << " " << a[co][i];
      }
      cout << endl;
    }
  }
}
